示例#1
0
def getHora():
    horas = datetime.now().hour
    minutos = datetime.now().minute
    segundos = datetime.now().second
    milisegundos = datetime.now().microsecond

    resultado = ''

    if horas <10:
        resultado += '0' + str(horas)
    else:
        resultado += str(horas)

    resultado += ':'

    if minutos <10:
        resultado += '0' + str(minutos)
    else:
        resultado += str(minutos)

    resultado += ':'
    if segundos <10:
        resultado += '0' + str(segundos)
    else:
        resultado += str(segundos)
        resultado += ':'

    if milisegundos <10:
        resultado += '0' + str(milisegundos)
    else:
        resultado += str(milisegundos)

    return resultado
示例#2
0
def get_hora() -> str:
    '''
    Devuelve la hora en forma to hh:mm:ss
    :return:
    '''
    horas = datetime.now().hour
    minutos = datetime.now().minute
    segundos = datetime.now().second
    resultado = ''

    if horas <10:
        resultado += '0' + str(horas)
    else:
        resultado += str(horas)

    resultado += ':'

    if minutos <10:
        resultado += '0' + str(minutos)
    else:
        resultado += str(minutos)

    resultado += ':'
    if segundos <10:
        resultado += '0' + str(segundos)
    else:
        resultado += str(segundos)

    return resultado
示例#3
0
文件: form3.py 项目: akayerov/Medic
def exp_to_excel_form3(doc, iperiod, iregion, mode, stat = None):    # mode = 0 по региону или группе больниц  mode = 1 - по конкретной больнице
    res =  calc_sum_form3(doc)
    speriod = get_period_namef(iperiod)
    sregion = get_region_name(mode,doc,iregion)
    if mode == 1:
        name_file = get_name("/static/Form/Form3.xlsx")
    else:
        name_file = get_name("/static/Form/Form3_All.xlsx")

    wb = openpyxl.load_workbook(name_file)
    sheet = wb.active
    sheet['B2'] = speriod
    sheet['B1'] = sregion
    if mode==0:
        sheet['B310'] = "Статистика по отчету"  
        sheet['B311'] = "Организаций предоставляющих, Всего"
        sheet['C311'] = stat.rec_all
        sheet['B312'] = "Отобрано в отчет, Всего"
        sheet['C312'] = stat.rec_fltr
        sheet['B313'] = "Завершено"
        sheet['C313'] = stat.rec_complete
        sheet['B314'] = "Согласование"
        sheet['C314'] = stat.rec_soglas
        sheet['B315'] = "Корректировка"
        sheet['C315'] = stat.rec_correct
        sheet['B316'] = "Редактирование"
        sheet['C316'] = stat.rec_edit


    startrow = 7 
    for i in range(0,296):
        srA = "B" + str(startrow + i)
        srB = "C" + str(startrow + i)
        sheet[srA] = res[i][0]
        sheet[srB] = res[i][1]
# вывод только для конкретной МО для все  не выводится        
    if mode == 1:
#        res = calc_valf3_form2(doc)
        startrow = 307 
        for i in range(0,38):
            srA = "B" + str(startrow + i)
            srB = "C" + str(startrow + i)
            sheet[srA] = res[i][0]
            sheet[srB] = res[i][1]
                
        sheet['A346'] = "Выведено в системе Мед+ " + str(datetime.now()) 
        sheet['A346'].font = Font(size=5)
    else:
        sheet['A318'] = "Выведено в системе Мед+ " + str(datetime.now()) 
        sheet['A318'].font = Font(size=5)
 
 #   name_file =  get_name("\\medicament\\Form\\rep" + str(int(random()*100000000)) + ".xlsx") 
    name_file =  get_name("/medicament/Form/rep" + str(int(random()*100000000)) + ".xlsx") 
    wb.save(name_file)
    
    return name_file
示例#4
0
def todolist(request, interval='all'):

    assert isinstance(request, HttpRequest)

    if request.method == 'GET' and 'search' in request.GET:
        search = request.GET['search']
        if not search:
           tasks = {}
        else:
           tasks = Task.objects.filter(Q(name__icontains=search) |
                                       Q(description__icontains=search) |
                                       Q(date__icontains=search))
        return render(request,
                      'app/todolist.html',
                      {
                          'title': 'ToDoList',
                          'year':datetime.now().year,
                          'message': "Hello",
                          'tasks': tasks,
                      })

    now = date.today()
    step = request.GET.get('step', timedelta(days=1))
    tasks = False
    gap = now
    if interval == 'today':
        gap = now
    elif interval == 'tomorrow':
        now += timedelta(days=1)
        gap = now
    elif interval == 'week':
        gap = now + timedelta(days=7)
    elif interval == 'month':
        gap = now + timedelta(days=31)
    elif interval == 'year':
        gap = now + timedelta(days=365)
    else:
        tasks = Task.objects.all()

    if not tasks:
        currentDay = str(now.year) + '-' + str(now.month) + '-' + str(now.day)
        nextDay = str(gap.year) + '-' + str(gap.month) + '-' + str(gap.day)
        tasks = Task.objects.filter(date__range=[currentDay, nextDay])

    return render(
        request,
        'app/todolist.html',
        {
            'title': 'ToDoList',
            'year':datetime.now().year,
            'message': "Hello",
            'tasks': tasks,

        }
    )
示例#5
0
文件: utils.py 项目: lyuden/crawler
def add_paginated_url(session, template, page, source_id, logger=None):
    url_string = re.sub(PAGINATOR_REGEXP, str(page), template)
    print(url_string, page)
    try:
        url = session.query(Urls).filter(Urls.url == url_string).one()
        url.active_at = datetime.now()
        if logger:
            logger.debug('Found {} in database with id = {}. Do nothing'.format(url_string, url.id))
    except:
        url = Urls(source_id=source_id, url=url_string, depth=0, alive_at=datetime.now())
        session.add(url)
示例#6
0
文件: multi_tail.py 项目: vshreyas/ai
 def process(self, line):
     try:
         msg = json.loads(line)
         if 'note' in msg and 'at' in msg:
             msg['input'] = self.filename
             self.que.put(msg)
         else:
             self.que.put({'# INVALID LINE':cgi.escape(line), 'timestamp': datetime.now().strftime("%b %d %Y %H:%M:%S")+ datetime.now(tzlocal()).tzname()})       
     except ValueError:
         self.que.put({'# INVALID LINE':cgi.escape(line), 'timestamp': datetime.now().strftime("%b %d %Y %H:%M:%S") + datetime.now(tzlocal()).tzname()})
         print(datetime.now().strftime("%b %d %Y %H:%M:%S %Z"))
示例#7
0
    def save(self, *args, **kw):

        # status = self.objects.get(pk=self.pk).order_status

        if self.order_status != 'Draft':
            if self.order_status == 'New':
                self.ordered_date = datetime.now()
            elif self.order_status == 'Reject' or 'Accept':
                self.responce_date = datetime.now()


        super(Order, self).save(*args, **kw)
示例#8
0
    def write_file(self, savefile=True):
        if self.write_lock:
            return

        group_name = self.files_combobox.itemText(self.current_group_idx)
        if savefile:
            now = datetime.now().strftime('%Y_%m_%d_%H_%M_%S')
            file_name = 'Saves/{}_{}.csv'.format(group_name, now)
        else:
            file_name = QFileDialog.getSaveFileName(self, 'Export', group_name + '_ueX.csv', 'CSV (*.csv)')[0]
            if not file_name:
                return

        if not os.path.exists('Saves'):
            os.makedirs('Saves')

        with io.open(file_name, 'w', encoding='utf-8', newline='') as f:
            f.write('MatrNr;Gruppe;Kontrolle;Kommentar\n')
            for idx in range(self.table_widget.rowCount()):
                if self.table_widget.item(idx, 1).text():
                    f.write('{};{};{};{}% {}\n'.format(
                        self.table_widget.item(idx, 1).text(),
                        self.table_widget.item(idx, 2).text() or '0',
                        'an' if self.checked_list[idx].isChecked() else 'ab',
                        self.table_widget.item(idx, 4).text() or '0',
                        self.table_widget.item(idx, 5).text()
                    ))

        self.history_files.append(file_name[6:])
        self.history_index = len(self.history_files) - 1
示例#9
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 лет')
示例#10
0
def saveall():
    """
        Save all the table of the data base on the Excel document.
        
    """
    
    t=time()
    clearall(datetime.now())
    module_dir = os.path.dirname(__file__)
    file_path = os.path.join(module_dir, 'sauvegarde.xlsx')
    file_path2 = os.path.join(module_dir, 'tempo.xlsx')
    wb = openpyxl.load_workbook(file_path)
    svallpers(wb)
    svallgrp(wb)
    svallcour(wb)
    svallcour2(wb)
    svalluv(wb)
    svallmodu(wb)
    svallnot(wb)
    svallsal(wb)
    svallmod(wb)
    wb.save(file_path2)
    wb2 = openpyxl.load_workbook(file_path2)
    wb2.save(file_path)
    t=time()-t
    print('done in', t, 'sec')
示例#11
0
 def __init__(self, url, document, deadline=None, company=None, location=None, title=None):
     self.title = title
     self.document = document
     self.url = url
     self.deadline = deadline
     self.company = company
     self.location = location
     self.date = datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
示例#12
0
 def __init__(self, hotelPackageOrder, operation_user):
     self.hotelPackageOrder = hotelPackageOrder
     self.operation_user = operation_user
     self.customer = hotelPackageOrder.customer
     self.seller = hotelPackageOrder.seller
     self.cur_datetime = datetime.now()
     self.action = None
     self.orderBill = None
示例#13
0
    def _customer_cancel(self):
        # 当前订单状态 ,是否可以直接取消的操作
        # 判断当前预定的时间是否是免费的
        if self.hotelPackageOrder.process_state == HotelPackageOrder.CUSTOMER_REQUIRE:  # 如果商家未接单,全额退还
            self.hotelPackageOrder.process_state = HotelPackageOrder.CUSTOMER_CANCEL  # 标记为用户取消
            self.customer.add_customer_points(self.hotelPackageOrder.amount)
            # warn  全额退款 生成账单
        elif self.hotelPackageOrder.process_state == HotelPackageOrder.SELLER_ACCEPT:  # 商家已接单

            # warn 商家已接单
            hotelPackageOrderItems = self.hotelPackageOrder.items.select_subclasses()
            checkin_time = self.hotelPackageOrder.checkin_time

            # 入住当天6点的时间
            deduct_all_point_time = datetime(checkin_time.year, checkin_time.month, checkin_time.day,
                                             hour=18)  # 晚于这个时间扣除全部积分 (相当于默认的入住时间)

            # 入住前一天2点的时间
            dedcut_halt_point_time = deduct_all_point_time - timedelta(hours=28)  # 入住前一天的2点之后扣除一半

            self.hotelPackageOrder.process_state = HotelPackageOrder.CUSTOMER_BACK

            if self.cur_datetime < dedcut_halt_point_time:  # 未到扣除积分的时间
                self.hotelPackageOrder.process_state = HotelPackageOrder.CUSTOMER_CANCEL
                self.customer.add_customer_points(self.hotelPackageOrder.amount)
                # warn 同样的 也是i用户取消
            else:

                now = datetime.now()
                if self.cur_datetime < deduct_all_point_time:  # 扣除一半
                    need_deduct_poins = hotelPackageOrderItems[0].point * 0.5

                    if len(hotelPackageOrderItems) > 1 and now.hour >= 14:
                        need_deduct_poins += hotelPackageOrderItems[1].point * 0.5

                    need_back_to_customer_point = int(self.hotelPackageOrder.amount - need_deduct_poins)
                    orderBill = OrderBill.create_for_roomOrder_cancel(roomOrder=self.hotelPackageOrder,
                                                                      refund_amount=need_back_to_customer_point)
                    self.orderBill = orderBill
                else:  # 扣除当天全部 改代理商 %75
                    need_deduct_poins = hotelPackageOrderItems[0].point

                    if len(hotelPackageOrderItems) > 1 and now.hour >= 14:
                        need_deduct_poins += hotelPackageOrderItems[1].point * 0.5
                    need_back_to_customer_point = int(self.hotelPackageOrder.amount - need_deduct_poins)

                    orderBill = OrderBill.create_for_roomOrder_cancel(roomOrder=self.hotelPackageOrder,
                                                                      refund_amount=need_back_to_customer_point)

                    self.orderBill = orderBill
                self.hotelPackageOrder.success = True
                self.hotelPackageOrder.settled = True
        # TODO 如果
        self.hotelPackageOrder.closed = True
        self.hotelPackageOrder.success = True
        self.hotelPackageOrder.settled = True
 def update(self, message):
     super().logger.debug("User {} adding link".format(self.user.user_id))
     if (datetime.now() - self.time).total_seconds() \
             > config.awaitance:
         self.user.callback(bot_strings.awaitance_time_exceeded)
         return BasicState.create_transition(StateTags.MAIN)
     if message in bot_strings.cancel_id:
         return BasicState.create_transition(StateTags.MAIN)
     super().logger.debug("User {} trying link {}".format(self.user.user_id, message))
     return BasicState.create_transition(StateTags.ADD_LINK_TAG, link=message)
示例#15
0
    def getFilteredTxt(self):

        timeStart = formatTime(subtractTime('m',60))

        timeEnd = formatTime(str(datetime.now()))


        c.execute("SELECT FTxt FROM tbl_FilteredText WHERE time_FTextRec BETWEEN ? AND ?", (timeStart, timeEnd))
        r = c.fetchall()

        return  r
示例#16
0
    def __init__(self, id, provider_id, secret, user_id, secret_hashed = False, expires_ts = None, created_ts = None):
        super().__init__(id)

        self._validate_provider_id(provider_id)
        self._set_attr("provider_id", provider_id)
        self._set_secret(secret,secret_hashed)
        
        self._set_attr("user_id", user_id)
        
        self._set_attr("expires_ts",expires_ts)
        self._set_attr("created_ts",created_ts, datetime.now())
def downloadMarc(directory, url,collIDName):
    todayDate = datetime.now()
    eDate = str(todayDate.year)+'-'+str(todayDate.month)+'-'+str(todayDate.day)
    req = requests.get(url)
    marcfileName = 'Project_MUSE_UPCC_'+str(collIDName)+'_'+str(eDate).replace("-", '')+'.mrc'
    path = directory
    fileName = os.path.join(path, marcfileName)

    with open(fileName, 'wb') as x:
        x.write(req.content)
    print('saved '+fileName)
示例#18
0
def home(request):
    """Renders the home page."""
    assert isinstance(request, HttpRequest)
    return render(
        request,
        'app/index.html',
        {
            'title':'Home Page',
            'year':datetime.now().year,
        }
    )
示例#19
0
    def is_valid(self):

        now = datetime.now()
        current_time = now.strftime("%H:%M:%S")

        if self.debut_heure_arrivee.strftime(
                "%H:%M:%S") < current_time and self.fin_heure_arrivee.strftime(
                    "%H:%M:%S") > current_time:

            return True
        else:
            return False
示例#20
0
    def stopRun(run_day_id):
        pst = pytz.timezone('Australia/Perth')
        now = datetime.now(pst)
        rd = RunDay.objects.filter(id=run_day_id)

        ReticEngine.closeValvesDB()

        for s in rd:
            s.last_updated_by = 0
            s.last_update_date = now
            s.run_status = 'Stopped'
            s.save()
示例#21
0
def qregister(request):
        #사용자의 요청방식을 구분
        #GET방식 -> HTML을 전달
        if request.method == "GET":
            #Form클래스 이용방법
            #객체 생성 후 as_p, as_table, as_ul 함수를
            #호출하면 <input>태그를 자동생성해줌
            form = QuestionForm()
            print(form.as_p())
            #입력양식을 행,열단위로 HTML코드 생성
            html = form.as_table()
            return render(request,'vote/qform.html',
                                        {'form' : html})
        # POST방식 -> 사용자 입력기반의 Question객체 생성
        elif request.method == "POST":
            # request.POST : 사용자 입력 데이터 저장 변수
            # 사용자가 보낸 데이터를 기반으로 QuestionForm
            # 객체 생성
            form = QuestionForm(request.POST)
            # 사용자가 보낸 데이터가 유효한 값인지 확인
            if form.is_valid():
                """
                폼객체.is_valid() : 사용자 입력이 유효한경우 True반환,
                추가적으로 cleaned_data 변수를 사용해 데이터를 추출할수있음
                만약에 유효한값이 아닌경우 False반환,
                사용자의 입력을 다시 받을 수 있도록 HTML코드를 전달    
                
                모델폼객체는 연동된 모델객체를 생성할 수 있음
                모델폼객체.save() : 반환값 생성된 모델객체.
                내부적으로 데이터베이스에 새로운 객체가 저장됨
                현재 QuestionForm객체로 title변수만 값이 작성되있어
                데이터베이스에 바로 저장을 할 수 없음(pub_date변수값없음)
                
                모델폼객체.save(commit=False) : 데이터베이스에 저장하지않고,
                모델객체만 반환함
                """
                # form 객체와 연동된 모델객체를 q변수에 저장
                # q : Question객체를 저장한 상태
                q = form.save(commit=False)
                print('생성할 객체의 제목', q.title)
                print('id 변수값 : ' , q.id)
                # 새로 생성할 객체에 서버컴퓨터의 현재날짜를 저장
                q.pub_date = datetime.now()
                # 객체를 데이터베이스에 저장
                q.save()
                print('객체 생성 후 id 변수값 : ', q, id)
                # reverse 함수 :  파이썬 코드내에서 별칭기반으로
                # URL을 찾을 수 있는 함수
                # reverse(별칭 문자열, args=(매개변수값,))
                # index 뷰함수 호출
                return HttpResponseRedirect(reverse('vate:index'))
            else:
                    pass
示例#22
0
def contact(request):
    """Renders the contact page."""
    assert isinstance(request, HttpRequest)
    return render(
        request,
        'app/contact.html',
        {
            'title':'Contact',
            'message':'My contact page.',
            'year':datetime.now().year,
        }
    )
示例#23
0
    def deamon(self):
        '''Deamon method, which is used for logging off users, who are inactive for the specified time'''
        while True:
            sleep(10)
            

        minute = 30
        time = datetime.now() - timedelta(minutes = minute).strftime('%Y%m%d%H%M%S')

        for i in self.r.zrangebyscore('active', -inf, time):
            self.r.hdel('tokens', i)
            self.r.zrem('active', i)
示例#24
0
def getSavedData(reload=False):
	if reload:
		tickers = fetchData()
	else:
		with open("stocks.pickle","rb") as f:
			tickers = pickle.load(f)
	start = dt.datetime(2010,1,1)
	end = dt.datetime(datetime.now().year,datetime.now().month,int((dt.date.today() - dt.timedelta(days=1)).strftime('%d')))
	if not os.path.exists('stocks'):
		os.makedirs('stocks')
	for ticker in tickers:
		if not os.path.exists('stocks/{}.csv'.format(ticker)):
			time.sleep(0.5)
			df = web.DataReader(ticker,'yahoo',start,end)
			df.to_csv('stocks/{}.csv'.format(ticker))
			print(ticker + " saved.")
		else:
			print("Already have {}".format(ticker))
	print()
	print()
	return tickers
示例#25
0
文件: user.py 项目: intelmix/legacy
 def sign_up(self,email,username,password):
     cnt = User.select().where( (User.email == email) | (User.username == username)).count()
     if cnt == 0:
         u = User(email=email,username=username,password=password,register_date=datetime.now())
         u.save()
         return True
     else:
         return False
     
     print (cnt)
     return True
     pass
示例#26
0
def about(request):
    """Renders the about page."""
    assert isinstance(request, HttpRequest)
    return render(
        request,
        'app/about.html',
        {
            'title':'About',
            'message':'My simple ToDoList',
            'year':datetime.now().year,
        }
    )
示例#27
0
    def get(self, request, item_id):
        response = requests.get(url)
        data = response.json()

        # Your JSON object
        if request.session.get('currency_code') is None:
            request.session['currency_code'] = "EUR"

        usd_rate = data["rates"][request.session.get('currency_code')]

        auction = Auction.objects.get(id=item_id)
        auctions = Auction.objects.filter(status="Active")
        bidding_all = Bidding.objects.filter(
            auction_id=item_id).order_by('-new_price')
        biddings = Bidding.objects.filter(
            auction_id=item_id).order_by('new_price').last()

        # Converting auction price to usd and vice versa
        new_pris = round(float(auction.minimum_price) * usd_rate, 2)
        auction.minimum_price = new_pris

        # Converting all biddings price
        if bidding_all is not None:
            for item in bidding_all:
                item.new_price = round(float(item.new_price) * usd_rate, 2)

        # Converting the current highest bid
        if biddings is not None:
            biddings.new_price = round(float(biddings.new_price) * usd_rate, 2)

        delta = auction.deadline_date - datetime.now(timezone.utc)

        current_version = auction.version
        request.session['value'] = current_version

        if auction.status == "Banned":
            messages.info(request, "You can only bid on active auction")
            return render(request, "home.html", {"auctions": auctions})
        elif auction.hosted_by == request.user.username:
            messages.info(request, "You cannot bid on your own auctions")
            return render(request, "home.html", {"auctions": auctions})
        elif delta.total_seconds() <= 0:
            messages.info(request, "You can only bid on active auction")
            return render(request, "home.html", {"auctions": auctions})
        else:
            form = BiddingForm()
            return render(
                request, "bid_auction.html", {
                    "form": form,
                    "auction": auction,
                    "biddings": biddings,
                    "bidding_all": bidding_all
                })
示例#28
0
def aborttemp(event=None):
    state = "... IN ABORT STATE ..."
    mlist.insert(tkinter.END, state)
    msg = "Global-Abort"
    tdate = datetime.now()
    msglen = len(msg)
    http = "HTTP/1.1 200 OK " + time.ctime()
    date = "Date: " + str(tdate)
    server = "Server: JetBrains Pycharm 2017"
    content = "Content Length: " + str(msglen)
    fullmsg = http + "," + date + "," + msg + "," + server + "," + content
    client_socket.send(bytes(fullmsg, "utf8"))
示例#29
0
def get_data():
    entry_dict = request.get_json()
    travel, path, c = [], [], 0
    if entry_dict['algo'] == "BFS":
        a = dt.now()
        travel, path = BFS(entry_dict['start'], entry_dict['end'], entry_dict['blocks'], entry_dict['options']).find()
        b = dt.now()
        c = b-a

    elif entry_dict['algo'] == "a-star":
        a = dt.now()
        travel, path = AStarFinder(entry_dict['start'], entry_dict['end'], entry_dict['blocks'], entry_dict['options'], entry_dict['heuristic'], entry_dict['weight']).find()
        b = dt.now()
        c = b-a

    elif entry_dict['algo'] == "Dijkstra":
        a = dt.now()
        travel, path = DijkstraSearch(entry_dict).find()
        b = dt.now()
        c = b-a

    elif entry_dict['algo'] == "best-first":
        a = dt.now()
        travel, path = BestFirstSearch(entry_dict['start'], entry_dict['end'], entry_dict['blocks'], entry_dict['options'], entry_dict['heuristic']).find()
        b = dt.now()
        c = b-a

    elif entry_dict['algo'] == "Teleport":
        a = dt.now()
        travel, path = PortFinder(entry_dict['start'], entry_dict['end'], entry_dict['blocks'], entry_dict['options'], entry_dict['ports']).find()
        b = dt.now()
        c = b-a

    result = {
        'traversal': travel,
        'path': path,
        'time': c.microseconds/1000
    }
    res = make_response(jsonify(result), 200)
    return res
示例#30
0
def analysis_fb_page(shop_name: str, contents: str, url: str):

    content_list: list = contents.split(shop_name)
    content_list = content_list[1:-1]

    for c in content_list:
        if "口罩" in c:
            post_time, post_content = extract_fb_post_text(c)
            today_date = datetime.now()

            on_sale = detect_on_sale(post_content)

            if post_time is None:
                break

            if on_sale:
                if post_time.month == today_date.month and post_time.day == today_date.day:
                    selling = True
                else:
                    selling = False
                load_to_dict(shop_name, selling, datetime_to_str(post_time),
                             beautify_content(post_content), url)
                break

            elif on_sale is False:
                load_to_dict(shop_name, False, datetime_to_str(post_time),
                             beautify_content(post_content), url)
                break

            elif on_sale is None:
                pass

    dict_key = re.sub('[\u4e00-\u9fa5]', '', shop_name).replace(" ", "")
    if dict_key not in posts_dict:
        load_to_dict(shop_name, False, datetime_to_str(datetime.now()),
                     f"Cannot find recent facemask sales info", url)

    print_time_and_msg(f"Finish analysing {shop_name}...")

    return posts_dict
示例#31
0
def convert_str_to_time(time_str: str) -> datetime:
    if len(re.findall(r"\d+\s*分鐘", time_str)) > 0:
        minute = timedelta(minutes=int(re.findall(r"(\d+)\s*分鐘", time_str)[0]))
        return datetime.now() - minute

    elif len(re.findall(r"\d+\s*小時", time_str)) > 0:
        hour = timedelta(hours=int(re.findall(r"(\d+)\s*小時", time_str)[0]))
        return datetime.now() - hour

    elif "昨天" in time_str:
        no_in_str = re.findall(r"\d+", time_str)
        hour = int(no_in_str[0])
        minute = int(no_in_str[1])

        return datetime(datetime.now().year,
                        datetime.now().month,
                        datetime.now().day - 1, hour, minute, 00)

    elif len(re.findall(r"\d+\s*月\d+\s*日", time_str)) > 0:
        no_in_str = re.findall(r"\d+", time_str)
        print(time_str)

        month = int(no_in_str[0])
        date = int(no_in_str[1])
        hour = int(no_in_str[2])
        minute = int(no_in_str[3])
        return datetime(datetime.now().year, month, date, hour, minute, 00)

    else:
        pass
示例#32
0
    def get_presets(self):
        viewdata = {"day": [], "week": [], "month": []}
        for name in MqttWaterLevelData.objects.all().values(
                "hardware_serial").distinct():
            all_for_station = MqttWaterLevelData.objects.all().filter(
                hardware_serial=name["hardware_serial"]).order_by('-time')
            day = []
            week = []
            month = []
            for item in all_for_station:
                cur_time = datetime.fromtimestamp(int(item.time[0:10]))
                if cur_time > datetime.now() - timedelta(days=30):
                    month.append((item.time, item.river_height_mm))
                if cur_time > datetime.now() - timedelta(days=7):
                    week.append((item.time, item.river_height_mm))
                if cur_time > datetime.now() - timedelta(days=1):
                    day.append((item.time, item.river_height_mm))

            viewdata["day"].append({
                "id": name,
                "time_reading": day,
                "lat": all_for_station[0].latitude,
                "long": all_for_station[0].longitude,
            })

            viewdata["week"].append({
                "id": name,
                "time_reading": week,
                "lat": all_for_station[0].latitude,
                "long": all_for_station[0].longitude,
            })

            viewdata["month"].append({
                "id": name,
                "time_reading": month,
                "lat": all_for_station[0].latitude,
                "long": all_for_station[0].longitude,
            })

        return viewdata
示例#33
0
def checkHolds(port, driver):
    driver.find_element_by_id("clayView:ns_7_40O00G3VMR0D00A4BG79CQ0087_00000:_idsc00001:_idsc00003_6:_idsc00007").click()
#     driver.find_element_by_id("clayView:ns_7_40O00G3VMR0D00A4BG79CQ00Q4_00000:_idsc00001:portId").send_keys(port)
    driver.find_element_by_id("clayView:ns_7_40O00G3VMR0D00A4BG79CQ00Q4_00000:_idsc00001:_idsc00020").click()
    
    onHold = []
    bonds = []
    done = False    
    j=2
    driver.implicitly_wait(0)
    try:
        driver.find_element_by_css_selector("span[title='Page 1']").click()
    except:
        pass
    driver.implicitly_wait(60)  
    while not done:
        cells = driver.find_elements_by_css_selector("table[class='datat']>tbody>tr>td")
        i=0
        while i<min(1500, len(cells)):
            driver.execute_script("arguments[0].scrollIntoView();", cells[i])
#             bonds.append(cells[i+3].text)
#             if not todaysDate in cells[i+10].text:
            if "Y" in cells[i+14].text:
                onHold.append(cells[i+3].text)
#                 cells[i+3].find_element_by_tag_name("input").send_keys(port)
            i+=15
#             else:
#                 break
        driver.implicitly_wait(0)
        try:
            driver.find_element_by_css_selector("span[title='Page " +str(j)+ "']").click()
            j+=1
        except:
            done=True
        driver.implicitly_wait(60)  
    
    if len(bonds)>0:
        filepath = r"J:\INBOND CLOSURE TRACKING\Open Bonds - " + datetime.now().strftime("%Y-%m-%d %H-%M-%S") + ".xlsx"  
        wb = Workbook()
        ws = wb.active
        for i in range(len(bonds)):
            ws.cell(row=i+1, column=1).value = bonds[i]
        wb.save(filepath)
    
    if len(onHold)>0:
        print("IN-BOND #S ON HOLD:")
        holdString = "IN-BOND #S ON HOLD:\n"
        for bond in onHold:
            print(bond)
            holdString = holdString+bond + "\n"
        
        HelperFunctions.popUpOK(holdString)
def import_profile_data(uid: long):
    p = Profile()
    p.drop_collection()
    p.user_id = uid
    p.has_kyc = True
    p.military_service_status = ProfileMilitaryServiceStatusEnum.FINISHED
    p.sim_card_ownership = True
    p.address_verification = True
    p.membership_date = datetime.now()
    p.recommended_to_others_count = 3
    p.star_count_average = 2
    p.score = 0
    gs.save_document(p)
示例#35
0
def parse_database(app_data, max_age, fake=False):
    """
    Parse database and remove too old jobs (from database and from disk)

    :param app_data: folder where jobs are stored
    :type app_data: str
    :param max_age: remove all files & folders older than this age. Define it for each category
        (uploads, data, error, ...)
    :type max_age: dict
    :param fake: if True, just print files to delete, without delete them
    :type fake: bool
    :return: id jobs which are in the gallery (not removed independently of their age)
    :rtype: list
    """
    from dgenies.database import Job, Gallery
    gallery_jobs = []
    with Job.connect():
        old_jobs = Job.select().where(
            ((Job.status == "success") & (Job.date_created < datetime.now() -
                                          timedelta(days=max_age["data"])))
            | ((Job.status != "success") & (Job.date_created < datetime.now() -
                                            timedelta(days=max_age["error"]))))
        for job in old_jobs:
            id_job = job.id_job
            is_gallery = len(
                Gallery.select().join(Job).where(Job.id_job == id_job)) > 0
            if is_gallery:
                gallery_jobs.append(id_job)
            else:
                print("Removing job %s..." % id_job)
                data_dir = os.path.join(app_data, id_job)
                if os.path.exists(data_dir) and os.path.isdir(data_dir):
                    if not fake:
                        shutil.rmtree(data_dir)
                else:
                    print("Job %s has no data folder!" % id_job)
                if not fake:
                    job.delete_instance()
    return gallery_jobs
示例#36
0
def create_comment(request):
    json = request.json_body
    id_question = json['id_question']
    comment = json['comment']

    complete_question = request.db_session.query(CompleteQuestion).filter_by(id=id_question).one()
    complete_question.comment = comment
    complete_question.date_mdf = datetime.now()
    request.db_session.merge(complete_question)

    request.db_session.flush()

    return 0
示例#37
0
def log_to_file(args, accuracy) -> str:
    log_dir = "logs"
    if not os.path.exists(log_dir):
        os.mkdir(log_dir)
    t = datetime.now()
    filename = f"{t.year}-{t.month}-{t.day}_{t.hour}-{t.minute}-{t.second}.txt"
    filepath = os.path.join(log_dir, filename)
    with open(filepath, "w+") as f:
        args_dict = args.__dict__
        for k, v in args_dict.items():
            f.write(f"{k}: {v}\n")
        f.write(f"accuracy: {accuracy}\n")
    return filepath
示例#38
0
 def test_register_employee(self):
     employee = EmployeeProvider.create_simple("Some Name", "some_password", "*****@*****.**")
     now_date = datetime.now()
     employee = EmployeeProvider.register(employee=employee,
                                          employment_date=now_date,
                                          balance_vac=5)
     self.assertIsNotNone(employee)
     self.assertEqual(employee.registration_date.year, now_date.year)
     self.assertEqual(employee.registration_date.month, now_date.month)
     self.assertEqual(employee.registration_date.day, now_date.day)
     self.assertEqual(employee.employment_date, now_date)
     self.assertEqual(employee.activated, True)
     self.assertEqual(employee.vacation, 5)
def get_dates(days_to_get=4):
    """
    Returns a list of dates from today to 3 days ago in year, month, day format
    :param days_to_get: # of days to get from api
    :return: list of string of dates in year, month, day format
    """
    dates = []
    for i in range(0, days_to_get):
        # get dates
        date = datetime.now() - timedelta(days=i)
        # append in year month date format
        dates.append(date.strftime('%Y%m%d'))
    return dates
示例#40
0
            def after_run(self, run_context, run_values):
                if self._step % FLAGS.log_frequency == 0:
                    current_time = time.time()
                    duration = current_time - self._start_time
                    self._start_time = current_time

                    [loss_value, lr] = run_values.results
                    examples_per_sec = FLAGS.log_frequency * FLAGS.batch_size / duration
                    sec_per_batch = float(duration) / FLAGS.log_frequency

                    format_str = '%s : step %d, loss = %.2f (%.1f examples/sec; %.3f sec/batch, learning rate:%.6f)'
                    print(format_str % (datetime.now(), self._step, loss_value,
                                        examples_per_sec, sec_per_batch, lr))
示例#41
0
    def addValue(self, val):
        print(val)
        self.count += 1
        self.timestamp = str(datetime.now())
        self.total += val
        self.currentValue = val

        if (val < self.minValue):
            self.minValue = val
        if (val > self.maxValue):
            self.maxValue = val
        if (self.count > 0 and self.total != 0):
            self.averageValue = self.total / self.count
示例#42
0
def utcoffset(lat, lng):
    """
    returns a location's time zone offset from UTC.
    """
    target = dict({'lat': lat, 'lng': lng})
    tz_target = timezone(
        tf.certain_timezone_at(lat=target['lat'], lng=target['lng']))

    print("target timezone: ", tz_target)
    # TODO: tz_target could be None! handle error case
    today_target = tz_target.localize(datetime.now())
    offset = today_target.strftime('%z')[0:3]  # +/-HHMM
    return int(offset)
示例#43
0
def process_data_plotly():
    """Reads .csv file into pandas dataframe and processes data
    for plotly
    """
    df = {}
    symbols = [
        'EUR/USD', 'USD/JPY', 'USD/CHF', 'USD/CAD', 'AUD/USD', 'GBP/USD',
        'NZD/USD'
    ]

    for i in range(len(symbols)):
        filename = ('historical_data_' + symbols[i].replace('/', '') + '_' +
                    str(datetime.now().date()) + '.csv')
        filepath = 'C:\\Users\\Indra\\PycharmProjects\\forex_tracker\\historical_data\\' + str(
            datetime.now().date())
        header = ['Open', 'High', 'Low', 'Close', 'Date']
        temp = pd.read_csv((filepath + '\\' + filename), names=header)
        temp = temp[['Date', 'Open', 'High', 'Low',
                     'Close']]  # rearrange column to fit mplfinance
        df[symbols[i]] = temp

    return df
示例#44
0
def test_invitations_status_expiry(session):  # pylint:disable=unused-argument
    """Assert can set the status from PENDING to EXPIRED."""
    sent_date = datetime.now() - timedelta(
        days=int(get_named_config().TOKEN_EXPIRY_PERIOD) + 1)
    invitation = factory_invitation_model(session=session,
                                          status='PENDING',
                                          sent_date=sent_date)
    session.add(invitation)
    session.commit()

    result: str = invitation.status

    assert result == 'EXPIRED'
示例#45
0
def ui_add(month, undo_list, amount, category):
    '''
    Adds to the current day the amount of money and in category tag
    
    Input:
    month - a dictionary that consists in a dictionary of "days" and a dictionary of "categories"
    day - day when amount was spent
    amount - sum that was spent
    category - type of amount spent
    '''
    undo_list.append(copy.deepcopy(month))
    add_expense(month, create_expense(str(datetime.now().day), amount,
                                      category))
示例#46
0
def main():
    start_time = datetime.now()
    try:
        sys.argv[1]
        print(sys.argv[1])
        ip = sys.argv[1]
        dot_count = 0
        for i, v in enumerate(ip):
            if v == '.':
                dot_count += 1

        if dot_count != 3:
            print("Invalid format")
            return

        # initialize the testing class if the input is valid
        tester = StressTester(ip)
    except IndexError:
        tester = StressTester()
        pass
    try:
        tester.stress_test()
    except Exception as e:
        print(e)
        return

    timings = []
    while not tester.q.empty():
        timings.append(tester.q.get())

    avg = 0
    for i in timings:
        avg += i.total_seconds()
        print (i)
    avg /= len(timings)
    print("Average = ", avg)
    time_it_took = datetime.now() - start_time
    print("Script ran for a total of ", time_it_took.total_seconds())
    print(tester.tasks/time_it_took.total_seconds(), " requests per second")
示例#47
0
def lock_data():
    while True:
        person_name = input("Enter Person Name: ")
        if person_name.lower() == "q":
            break
        elif person_name.lower() == "farrukh" or person_name.lower(
        ) == "taha" or person_name.lower() == "usama" or person_name.lower(
        ) == "umair":
            person_name += ".txt"
            c = 0
            try:
                content = open(person_name, "a")
                val = open(person_name, "r")
            except:
                print("file not found!")
            date = datetime.now()
            month = int(date.month)
            c_month = month
            if val.read() == "":
                content.write(f"{month}")
            else:
                with open(person_name, "r") as value:
                    c_mon = value.read()
                    c_month = c_mon[len(c_mon) - 1]
            if int(month) == int(c_month):
                amount = input("Enter Amount: ")
                date = datetime.now()
                month = int(date.month)
                str = f"-- Month and Date: \'{date}\'\n    Amount: \'{amount}\'\n"
                content.write(str)
                content.write(
                    "    ------------------------------------------\n")
                content.write(f"{month+1}")
                val.close()
                content.close()
            else:
                print("You already enter the amount of this month!")
        else:
            print("Enter valid name")
def write_to_file(item):
    """
    Function to write the wanted information to a csv file. It adds the current month to the filename which means you
    will get a new file on the 1st of every month.
    It will append any new sentences to the file for the current month, each time the script runs.
    """
    current_date = datetime.now()
    current_month = current_date.strftime("%b")
    f = open("Your Filename %s.csv" % current_month, "a+")
    f.write(
        item + "\n"
    )  # write each item to the file with a line break at the end - will write each item on a new line
    f.close()
示例#49
0
 def test_is_deployed_false_if_desiredCount_not_equals_runningCount(self):
     service = {
         "desiredCount":
         201,
         "runningCount":
         200,
         "pendingCount":
         1,
         "deployments": [{
             'id': 'ecs-svc/1234567891012345679',
             'status': 'PRIMARY',
             'taskDefinition':
             'arn:aws:ecs:us-west-2:123456789101:task-definition/SuperTaskFamily:513',
             'desiredCount': 201,
             'pendingCount': 1,
             'runningCount': 200,
             'createdAt': datetime.now(),
             'updatedAt': datetime.now(),
             'launchType': 'EC2'
         }]
     }
     assert not is_deployed(service)
示例#50
0
 def _extract_nowplaying(self, p_obj, p_playline):
     """
     """
     p_obj.From = self.m_pyhouse_obj.Computer.Name
     p_obj.DateTimePlayed = datetime.now()
     l_playline = p_playline
     p_obj.Song, l_playline = extract_quoted(l_playline, b'\"')
     p_obj.Artist, l_playline = extract_quoted(l_playline)
     p_obj.Album, l_playline = extract_quoted(l_playline)
     p_obj.Likability, l_playline = self._extract_like(l_playline)
     p_obj.Station, l_playline = self._extract_station(l_playline)
     p_obj.Status = 'Playing'
     return p_obj  # for debugging
示例#51
0
def comment_create_view(request):
    if request.method == "POST":
        new_comment = CommentForm()
        current_user = request.user
        my_p = User.objects.get(id=current_user.id)
        new_comment.user = my_p
        new_comment.comment = request.POST.get('comment')
        # new_comment.comment_date = parse_date(request.POST.get('comment_date'))
        new_comment.comment_date = datetime.now()
        print(new_comment.user)
        print(new_comment.comment_date)
        print(new_comment.comment)
        Comments.objects.create(user=new_comment.user,
                                comment=new_comment.comment,
                                comment_date=new_comment.comment_date)
    comments = Comments.objects.all()
    date = datetime.now()
    context = {
        'object': comments,
        'time': defaultfilters.date(date, "Y-m-d h:i A")
    }
    return render(request, "PyTraker/comment_form.html", context)
示例#52
0
 def parse_data(self, response):
     '''解析数据'''
     item = DishonestItem()
     data_str = json.loads(response.text)
     # print(len(data_str))
     # item['name'] = jsonpath(data_str, '$..iname')
     results = jsonpath(data_str, '$..result')[0]
     # print(len(results))
     for result in results:
         item['name'] = result['iname']
         item['age'] = result['age']
         item['area'] = result['areaName']
         item['business_entity'] = result['businessEntity']
         item['content'] = result['duty']
         item['card_number'] = result['cardNum']
         item['publish_date'] = result['publishDate']
         item['publish_unit'] = result['courtName']
         item['create_date'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
         item['update_date'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
         # print(item)
         yield item
     '''{"StdStg":6899,"StdStl":8,"_update_time":"1563185224","cambrian_appid":"0","changefreq":"always","age":"55","areaName":"安徽","areaNameNew":"安徽","businessEntity":"","cardNum":"3423011964****3224","caseCode":"(2019)皖1122执1194号","courtName":"来安县人民法院","disruptTypeName":"有履行能力而拒不履行生效法律文书确定义务","duty":"一、被告储成玲于本判决生效后十日内偿还原告张梅红借款人民币330000元及利息(自2019年3月13日起按年利率6%计算至付清之日止);","focusNumber":"0","gistId":"(2019)皖1122民初1103号","gistUnit":"安徽省来安县人民法院","iname":"储成玲","partyTypeName":"0","performance":"全部未履行","performedPart":"暂无","publishDate":"2019年07月13日","publishDateStamp":"1562947200","regDate":"20190709","sexy":"女性","sitelink":"http:\/\/zxgk.court.gov.cn\/","type":"失信被执行人名单","unperformPart":"暂无","lastmod":"2019-07-15T03:08:21","loc":"http:\/\/shixin.court.gov.cn\/detail?id=707091354","priority":"1.0","SiteId":2015330,"_version":269,"_select_time":1563179419}
示例#53
0
        def grid_draw(params):
            print(threading.get_ident(), datetime.now(), "grid_draw")
            frame = params[0]
            image = params[1]
            scores, boxes = detect(Image.fromarray(image), detr, transform)
            #print(scores)
            surface = pygame.surfarray.make_surface(image.swapaxes(0, 1))
            display.blit(surface, (0, 0))
            #for box in boxes:
            #    pygame.draw.rect(surface, (255,0,0), (box[0], box[1], box[2]-box[0], box[3]-box[1]), 2)
            plot_results(display, myfont, scores, boxes)

            pygame.display.flip()
示例#54
0
def update_points_in_question_showQ(request):

    incomplete_test= request.matchdict['incomplete_test']
    incomplete_test.date_mdf  = datetime.now()

    testid=incomplete_test.test_id
    json = request.json_body

    if request.userid is None:
        raise HTTPForbidden
    if request.userid is not incomplete_test.test.user_id:
        raise HTTPUnauthorized
    #nc - new comment
    if json['nc']:
        create_comment(request)
    #else update points
    else:
        points = json['points']
        id_question = json['id_question']

        complete_question = request.db_session.query(CompleteQuestion).filter_by(id=id_question).one()
        complete_question.date_mdf = datetime.now()
        qtype=complete_question.question.qtype

        if qtype is 'S' or 'C':
            answer = complete_question.complete_q_complete_answers
            for ans in answer:
                ans.points = float(points)/len(answer)
                request.db_session.merge(ans)

        elif qtype is 'O' or 'R':
            answer = request.db_session.query(Complete_answer).filter_by(complete_question=complete_question).one()
            answer.points=points
            request.db_session.merge(answer)

        request.db_session.flush()

    return HTTPFound(request.route_path('showtest', test_id=testid))
示例#55
0
def addTask(request):
    if request.method == 'POST':
        form = AddTask(request.POST)
        if form.is_valid():
            name = request.POST.get('name', '')
            description = request.POST.get('description', '')
            date = request.POST.get('date', '')
            completed = request.POST.get('completed', False)
            task = Task(name=name, description=description, date=date, completed=completed)
            task.save()
            return render(request, 'app/thanks.html', {'title':'Thanks', 'year':datetime.now().year, 'message': 'task added',})
    else:
        form = AddTask()
    return render(request, 'app/addtask.html', {'form': form, 'title':'AddTask', 'year':datetime.now().year, 'massage': 'addtask',})
示例#56
0
def get_attributes():
    path_to_attributes = os.path.join(os.path.dirname(os.getcwd()), 'attributes.json')
    print(path_to_attributes)
    attributes_file = open(path_to_attributes)
    result = json.load(attributes_file)
    attributes_file.close()
    current_datetime = datetime.now()
    current_date = current_datetime.strftime("%Y_%m_%d")
    attributes_date = result["Date"]
    if (current_date != attributes_date):
        for key in result:
            result[key] = 1
        result["Date"] = current_date
    return result
示例#57
0
文件: form4.py 项目: akayerov/Medic
def save_tab_form4(request, doc):
    # Табличные части
    # tab1000
    print(datetime.now())
    i = 1
    maxi = 1000
    for i in range(maxi):
        print("cycle=",i)
        table = 'tab1000'    
        tabrs = Doc4Tab1000.objects.filter(doc=doc)
        for tab in tabrs: 
            tab.c3 = request.POST[get_name_input(table,tab.row.id,"c3")]
            tab.c3 = i
            tab.c4 = request.POST[get_name_input(table,tab.row.id,"c4")]
            tab.save()
    # tab2000
        table = 'tab2000'    
        tabrs = Doc4Tab2000.objects.filter(doc=doc)
        for tab in tabrs: 
            tab.c3 = request.POST[get_name_input(table,tab.row.id,"c3")]
            tab.c4 = request.POST[get_name_input(table,tab.row.id,"c4")]
            tab.save()
    print(datetime.now())
示例#58
0
def calendar(request):
    """Renders the about page."""
    assert isinstance(request, HttpRequest)
    results = {'title': 'Calendar',

               'message':'Hello',
               'year':datetime.now().year,
               'tasks': Task.objects.all(),
              }
    return render(
        request,
        'app/calendar.html',
        results
    )
示例#59
0
    def start(self):
        self.writeLog("ожидание подключения")
        try:
            self.measureSocket.bind((Receiver.LOCAL_IP, Receiver.PORT))

            data, self.clientInfo = self.measureSocket.recvfrom(Receiver.BUFFER_SIZE)
            self.receivedPacketsCount += 1
            self.startTime = datetime.now()
            self.writeLog("проверка запущена")

            self.measureSocket.settimeout(Receiver.TIMEOUT)

            while True:
                self.measureSocket.recv(Receiver.BUFFER_SIZE)
                self.receivedPacketsCount += 1
                print("\r\t{} получено".format(self.receivedPacketsCount), end='')
                self.endTime = datetime.now()
        except socket.timeout:
            print("")
            self.writeLog("проверка завершена")

        self.measureSocket.close()
        self.sendResults()
示例#60
0
def adminObavijesti():
    if request.method == "GET":
        return render_template("admin_objave.html")
    elif request.method == "POST":
        try:
            poruka = Poruka()
            poruka.naslov = request.form["naslov"]
            poruka.tekst = request.form["tekst"]
            poruka.vrijeme = datetime.now()
            baseSession.add(poruka)
            baseSession.commit()
            return render_template("admin_objave.html")
        except(BaseException):
            redirect("/adminObavijesti")
    else:
        redirect("/")