Ejemplo n.º 1
0
def cleanports():
    allports = Port.query.filter_by(port_used=1).all()
    allvoiceports = Port.query.filter_by(port_used=1).all()
    for ports in allports:
        ordl = Order.query.filter_by(port_id=ports.port_id).first()
        if ordl is None:
            stmt = update(Port).where(Port.port_id == ports.port_id).values(port_used=2)
            db.session.execute(stmt)
            db.session.commit()
            flash('Port '+str(ports.port_no)+' gjennoprettet!')
        elif ordl.orderl_expire + dateutils.relativedelta(months=1) <= datetime.date.today():
            stmt = update(Port).where(Port.port_id == ports.port_id).values(port_used=2)
            db.session.execute(stmt)
            db.session.commit()
            flash('Port '+str(ports.port_no)+' gjennoprettet!')
        else:
            flash('Ingen spillporter tilbakestillt!')
    for ports in allvoiceports:
        ordl = VtOrder.query.filter_by(port_id=ports.port_id).first()
        if ordl is None:
            stmt = update(Port).where(Port.port_id == ports.port_id).values(port_used=2)
            db.session.execute(stmt)
            db.session.commit()
            flash('Port '+str(ports.port_no)+' gjennoprettet!')
        elif ordl.orderl_expire + dateutils.relativedelta(months=1) <= datetime.date.today():
            stmt = update(Port).where(Port.port_id == ports.port_id).values(port_used=2)
            db.session.execute(stmt)
            db.session.commit()
            flash('Port '+str(ports.port_no)+' gjennoprettet!')
        else:
            flash('Ingen spillporter tilbakestillt!')
Ejemplo n.º 2
0
def eventsJson(request):
    month_start = datetime.datetime(timezone.now().year, timezone.now().month, 1, 0)
    next_month = month_start+relativedelta(months=+1)
    month_end = next_month+relativedelta(seconds=-1)
    
    data = serializers.serialize("json", Event.objects.all())
    return HttpResponse(data, content_type="text/plain")
Ejemplo n.º 3
0
def index(request):

    zone_usages = ZoneUsage.objects.filter_user(request.user)[:20]

    dt = datetime.datetime.now()

    if 'month' in request.GET:
        month = request.GET['month']
        try:
            dt = datetime.datetime.strptime(month, "%Y-%m")
        except ValueError:
            pass

    previous_month = dt - relativedelta(months=1)
    next_month = dt + relativedelta(months=1)

    if next_month > datetime.datetime.now():
        next_month = None

    period_start = datetime.date(dt.year, dt.month, 1)
    period_end = dt + relativedelta(months=+1, seconds=-1)

    tool_usages, tool_usage_total = ToolUsage.objects\
        .filter_user_month(request.user, dt)

    return render(request, 'access/index.html', locals())
Ejemplo n.º 4
0
 def get_queryset(self):
     if self.pair in settings.PAIRS:
         percent_change = 0.0
         last_price = 0.0
         percent_spread = 0.0
         orders = self.queryset
         pair = self.pair
         previous_orders = orders.filter(
             pair=pair,
             created_at__gte=datetime.datetime.now() +
             dateutils.relativedelta(hours=-48),
             created_at__lt=datetime.datetime.now() +
             dateutils.relativedelta(hours=-24)).exclude(
                 status__in=('completed',
                             'cancelled')).order_by("-created_at")
         orders = orders.filter(
             pair=pair,
             created_at__gte=datetime.datetime.now() +
             dateutils.relativedelta(hours=-24)).exclude(
                 status__in=('completed',
                             'cancelled')).order_by("-created_at")
         bids_order = orders.filter(side="bid")
         asks_order = orders.filter(side="ask")
         volume = bids_order.aggregate(
             Sum("quantity"))["quantity__sum"] or 0
         max_price = bids_order.aggregate(Max("price"))["price__max"] or 0
         min_price = bids_order.aggregate(Min("price"))["price__min"] or 0
         best_bid_price = max_price or 0
         best_ask_price = asks_order.aggregate(
             Min("price"))["price__min"] or 0
         spread = best_ask_price - best_bid_price
         if bids_order.count():
             last_order = bids_order[0]
             last_price = last_order.price or 0
             if previous_orders.count():
                 last_prev_price = previous_orders.filter(
                     side="bid")[0].price
                 if last_prev_price:
                     percent_change = (last_price - last_prev_price
                                       ) * 100 / last_prev_price
                 previous_best_bid_price = previous_orders.filter(
                     side="bid").aggregate(Max("price"))["price__max"] or 0
                 previous_best_ask_price = previous_orders.filter(
                     side="ask").aggregate(Min("price"))["price__min"] or 0
                 previous_spread = previous_best_ask_price - previous_best_bid_price
                 if previous_spread:
                     percent_spread = (
                         spread - previous_spread) * 100 / previous_spread
         return {
             "currency": pair.split("_")[-1],
             "volume": float(volume),
             "change": percent_change,
             "last_price": float(last_price),
             "day_high": float(max_price),
             "day_low": float(min_price),
             "spread": percent_spread
         }
     else:
         raise APIException("Unknown pair")
Ejemplo n.º 5
0
def get_start_date(request):
    start_date = request.GET.get(
        'start_date',
        datetime.datetime.now() - relativedelta(years=1)
    ) or datetime.datetime.now() - relativedelta(years=1)
    if not isinstance(start_date, datetime.datetime):
        start_date = datetime.datetime.strptime(start_date, '%Y-%m-%d')

    return start_date.replace(day=1)
Ejemplo n.º 6
0
 def __init__(self, asset, timestamp, **delta_kwargs):
     super(TimeCutClose, self).__init__(type=OrderTypes.timecut_close,
                                        asset=asset)
     if isinstance(timestamp, datetime.datetime):
         self.timestamp = (timestamp +
                           relativedelta(**delta_kwargs)).timestamp()
     else:
         self.timestamp = (datetime.datetime.fromtimestamp(timestamp) +
                           relativedelta(**delta_kwargs)).timestamp()
Ejemplo n.º 7
0
def genDates(firstYear, lastYear):
    time = date(int(firstYear), 1, 1)
    string = time.strftime("%Y%m%d")
    while True:
        time = time + relativedelta(months=1)
        if ((time.year > int(lastYear))
                or (time > date.today() + relativedelta(months=-2))):
            break
        string = string + "/" + time.strftime("%Y%m%d")
    return string
    def __call__(self):

        investment_value = dict()
        buckets = PeriodCollate(self._period_start.date, self._period_end.date,
                                investment_bucket_generator, store_investment, frequency=self._period_size.frequency,
                                interval=self._period_size.interval)

        start_value = Decimal('0.0')
        start_value_date = self._period_start.date - relativedelta(days=1)
        currency = get_currency()

        for account in account_walker(self._investment_accounts, ignore_list=self._ignore_accounts):
            for split in get_splits(account, self._period_start.date, self._period_end.date):
                buckets.store_value(split)

            start_value += get_balance_on_date(account, start_value_date, currency)

            for key in buckets.container.keys():
                date_value = key + relativedelta(months=1) - relativedelta(days=1)
                investment_value[key] = investment_value.get(key, Decimal('0.0')) + get_balance_on_date(account,
                                                                                                        date_value,
                                                                                                        currency)

        results = self._generate_result()
        results['data']['start_value'] = start_value

        results['data']['income'] = sorted(
            [(time.mktime(key.timetuple()), value['income']) for key, value in buckets.container.iteritems()],
            key=itemgetter(0))

        results['data']['money_in'] = sorted(
            [(time.mktime(key.timetuple()), value['money_in']) for key, value in buckets.container.iteritems()],
            key=itemgetter(0))

        results['data']['expense'] = sorted(
            [(time.mktime(key.timetuple()), value['expense']) for key, value in buckets.container.iteritems()],
            key=itemgetter(0))

        results['data']['value'] = sorted(
            [[time.mktime(key.timetuple()), value] for key, value in investment_value.iteritems()],
        )

        results['data']['basis'] = sorted(
            [[time.mktime(key.timetuple()), Decimal('0.0')] for key in buckets.container.keys()],
            key=itemgetter(0)
        )

        monthly_start = start_value
        for index, record in enumerate(results['data']['basis']):
            record[1] += (monthly_start + results['data']['income'][index][1] + results['data']['money_in'][index][1] +
                          results['data']['expense'][index][1])
            monthly_start = record[1]

        return results
Ejemplo n.º 9
0
 def get_context_data(self, **kwargs):
     ctx = super(TodaysTransactionsListView,
                 self).get_context_data(**kwargs)
     ctx['chart_label'] = _('Previous 5 Days')
     end = timezone.now() - relativedelta(days=1)
     start = end - relativedelta(days=5)
     ledgers = (DailyLedger.objects.filter(
         created_on__range=(start, end),
         owner=self.request.user).order_by('created_on'))
     ctx['ledgers'] = [{
         'start': l.created_on.strftime('%b %d'),
         'balance': l.ending_balance or 0
     } for l in ledgers]
     return ctx
Ejemplo n.º 10
0
def response():
    receipt2 = request.args.get('orderRef')
    if receipt2 is not None:
        session['premium'] = 2
        subid = session['subid']
        ordid = session['orderid']
        ordercreate = datetime.date.today()
        ordexp = ordercreate + dateutils.relativedelta(months=session['mcmonths'])
        existquer = Order.query.filter_by(cust_id=session['userid']).first()
        if existquer is not None:
            updorder = update(Order).where(Order.cust_id == session['userid']).values(orderl_expire=ordexp, sub_id=int(subid), ordernumber=int(ordid))
            db.session.execute(updorder)
            db.session.commit()
            send_email('Din ordrereferanse fra Gameserver.no', ADMINS[0], session['email'],
                        render_template('receipt.txt', subid=str(subid), ordid=str(ordid), ordexp=str(ordexp), orderref=receipt2, totprice=session['mcprice']),
                        render_template('receipt.html', subid=str(subid), ordid=str(ordid), ordexp=str(ordexp), orderref=receipt2, totprice=session['mcprice']))
            return render_template('response.html', receipt=receipt2, subid=subid, totprice=session['mcprice'], ordid=ordid, ordexp=ordexp)
        else:
            order = Order(int(session['portid']), int(subid), int(ordid), ordercreate, ordexp, '1', int(session['userid']))
            db.session.add(order)
            db.session.commit()
            send_email('Din ordrereferanse fra Gameserver.no', ADMINS[0], session['email'],
                        render_template('receipt.txt', subid=str(subid), ordid=str(ordid), ordexp=str(ordexp), orderref=receipt2, totprice=session['mcprice']),
                        render_template('receipt.html', subid=str(subid), ordid=str(ordid), ordexp=str(ordexp), orderref=receipt2, totprice=session['mcprice']))
            return render_template('response.html', receipt=receipt2, subid=subid, totprice=session['mcprice'], ordid=ordid, ordexp=ordexp)
    else:
        return render_template('response.html', receipt='Din bestilling er avbrutt')        
Ejemplo n.º 11
0
    def preload_year(self, start_time, end_time):
        del self._data_cache  # force the GC to dispose of old data
        preload_start = start_time - dateutils.relativedelta(
            months=2)  # because who knows?
        preload_end = end_time + dateutils.relativedelta(months=10)

        logger.debug("Preloading %s - %s", preload_start, preload_end)
        cache = HDF5Cache(start=preload_start,
                          end=preload_end,
                          content=read_feature_data_dict_from_hdf5(
                              symbols=self.symbols,
                              start=preload_start,
                              end=preload_end,
                              filepath=self.filename,
                              timezone=self.data_timezone))
        return cache
Ejemplo n.º 12
0
def subadmin():
    form = SubManageForm()
    orders = Order.query.filter_by(order_payed=1).all()
    if request.method == 'POST' and request.form['submit'] == 'Legg til abonnement':
        subquer = Subscription(form.sub_name.data, form.sub_description.data,
                               form.sub_type.data, form.sub_mnd.data, form.sub_days.data, form.sub_hours.data,
                               form.sub_limit.data, form.sub_pris.data)
        db.session.add(subquer)
        db.session.commit()
        flash('Abonnementet har blitt lagt til!')
        return render_template('subadmin.html', form=form, orders=orders)
    if request.method == 'POST' and request.form['submit'] == 'Slett ubetalte abonnementer':
        unpayedorder = Order.query.filter_by(order_payed='2').all()
        for unpayed in unpayedorder:
            resetuser(unpayed.cust_id)
            cleanports()
        flash('Ubetalte abonnementer slettet!')
    if request.method == 'POST' and request.form['submit'] == u'Slett utl\xf8pte abonnementer':
        ordl = Order.query.filter_by(order_payed='1').all()
        for ordr in ordl:
            if ordr.orderl_expire + dateutils.relativedelta(months=1) <= datetime.date.today():
                resetuser(ordr.cust_id)
                cleanports()
        flash(u'Utl\xf8pte abonnementer slettet!')
        return render_template('subadmin.html', form=form, orders=orders)
    return render_template('subadmin.html', form=form, orders=orders)
Ejemplo n.º 13
0
    def get_user_by_time_context(self):
        months = []
        usercounts = []
        eusercounts = []
        iusercounts = []
        for m in range(24, -1, -1):
            d = self.today - relativedelta(months=m, day=1)
            months.append('\'{m}/{y}\''.format(m=d.month, y=d.year))

            usercounts.append(
                str(
                    RUBIONUser.objects.filter(
                        Q(first_published_at__lte=d)
                        & (Q(expire_at=None) | Q(expire_at__gte=d))).count()))
            iusercounts.append(
                str(
                    RUBIONUser.objects.filter(
                        Q(first_published_at__lte=d)
                        & (Q(expire_at=None) | Q(expire_at__gte=d))
                        & Q(is_rub=True)).count()))
            eusercounts.append(
                str(
                    RUBIONUser.objects.filter(
                        Q(first_published_at__lte=d)
                        & (Q(expire_at=None) | Q(expire_at__gte=d))
                        & Q(is_rub=False)).count()))
        return {
            'months': mark_safe(','.join(months)),
            'usercount': ','.join(usercounts),
            'eusercount': ','.join(eusercounts),
            'iusercount': ','.join(iusercounts)
        }
def get_age(nin):
    # Should sanitize first
    nin = sanitize(nin)

    year_part = int(nin[4:6])
    day_part = nin[0:2]
    month_part = nin[2:4]
    century = None

    # Century indicator
    i = int(nin[6:7])

    if i in (0, 1, 2, 3):
        century = "19"
    elif i == 4 and year_part < 37:
        century = "20"
    elif i == 4 and year_part > 36:
        century = "19"
    elif i in (5, 6, 7, 8) and year_part < 58:
        century = "20"
    elif i in (5, 6, 7, 8) and year_part > 57:
        century = "18"
    elif i == 9 and year_part < 38:
        century = "20"
    else:
        century = "19"

    # Get year from nin again, because we need it as a string
    year = int("{0}{1}".format(century, nin[4:6]))
    date = datetime.date(year, int(month_part), int(day_part))
    today = datetime.date.today()

    ts = dateutils.relativedelta(today, date)
    return ts.years
Ejemplo n.º 15
0
    def get_bill_months(today, months):
        current_month = today.strftime('%B')
        if months <= 1:
            return current_month

        first_month = (today - relativedelta(months=months - 1)).strftime('%B')
        return '%s - %s' % (first_month, current_month)
Ejemplo n.º 16
0
def amortize_transaction(entry):

    if len(entry.postings) != 2:
        raise ValueError(
            'Amortized transactions must have exactly two postings.')

    new_entries = []

    original_postings = entry.postings

    periods = entry.meta['amortize_months']

    amount = abs(entry.postings[0].units.number)
    currency = entry.postings[0].units.currency

    monthly_amounts = split_amount(amount, periods)

    for (n_month, monthly_number) in enumerate(monthly_amounts):
        new_postings = []
        for posting in entry.postings:
            new_monthly_number = monthly_number
            if posting.units.number < 0:
                new_monthly_number = -monthly_number
            new_posting = posting._replace(
                units=Amount(number=new_monthly_number, currency=currency))
            new_postings.append(new_posting)

        new_entry = entry._replace(postings=new_postings)
        new_entry = new_entry._replace(date=entry.date +
                                       relativedelta(months=n_month))
        if new_entry.date <= date.today():
            new_entries.append(new_entry)
    return new_entries
Ejemplo n.º 17
0
 def _delete_file(f):
     mtime = datetime.fromtimestamp(path.getmtime(f))
     last_day = calendar.monthrange(mtime.year, mtime.month)[1]
     if mtime < datetime.now() - relativedelta(
             months=2) and mtime.day != last_day and mtime.day != 1:
         return True
     return False
Ejemplo n.º 18
0
 def get(self, request, unit_id):
     """
     Return unit by id.
     """
     start_date = get_start_date(request)
     end_date = get_end_date(request)    
     readings = MeterReading.objects.filter(
         unit=unit_id,
         date__gte=start_date,
         date__lte=end_date
     )
     result = []
     while(start_date < end_date):
         # add elec and water
         day_readings = list(filter(
             lambda x: datetime.datetime(year=x.date.year, month=x.date.month, day=x.date.day) == start_date,
             readings
         ))
         print(day_readings)
         if len(day_readings) == 2:
             total_reading = {
                 "unit": str(day_readings[0].unit.id),
                 "charge": day_readings[0].charge + day_readings[1].charge,
                 "date": day_readings[0].date
             }
             result.append(total_reading)
         start_date += relativedelta(days=1)
     return JsonResponse(result, safe=False)
Ejemplo n.º 19
0
    def __call__(self):
        today = date.today()

        trend_months = []
        for month_delta in self._trends:
            relative = today + relativedelta(months=month_delta)
            new_date = date(relative.year, relative.month, monthrange(relative.year, relative.month)[1])
            trend_months.append(new_date)

        delta_months = []
        for month_delta in self._deltas:
            relative = today + relativedelta(months=month_delta)
            new_date = date(relative.year, relative.month, monthrange(relative.year, relative.month)[1])
            delta_months.append(new_date)

        total_asset_data = self._calculate_payload(self._asset_definitions, delta_months, trend_months)
        total_liability_data = self._calculate_payload(self._liability_definitions, delta_months, trend_months,
                                                       liability=True)

        # Now to calculate the values for the net worth display
        net_worth_data = dict(current_data=total_asset_data['current_data'] + total_liability_data['current_data'],
                              deltas=[], trend=[])
        for index, trend in enumerate(trend_months):
            assets = total_asset_data['trend'][index]
            expenses = total_liability_data['trend'][index]
            net_worth_data['trend'].append(assets + expenses)

        for index, delta in enumerate(delta_months):
            assets = total_asset_data['delta_sub_total'][index]
            liability = total_liability_data['delta_sub_total'][index]
            net_value = assets + liability

            try:
                result = (net_worth_data['current_data'] - net_value) / net_value
                net_worth_data['deltas'].append(result)
            except:
                net_worth_data['deltas'].append('N/A')


        results = self._generate_result()
        results['data']['trend'] = [time.mktime(t.timetuple()) for t in trend_months]
        results['data']['deltas'] = self._deltas
        results['data']['assets'] = total_asset_data
        results['data']['liability'] = total_liability_data
        results['data']['net_worth'] = net_worth_data

        return results
Ejemplo n.º 20
0
def fetch_ged_events(country: int,
                     year: int,
                     month: int,
                     page_size=10,
                     politeness=.5):
    """
    Get all GED events for a single month from the UCDP GED api 
    """
    start_date = date(year=year, month=month, day=1)
    end_date = (start_date + relativedelta(months=1)) - relativedelta(days=1)

    logger.info("Fetching %s for %s", f"{str(year)[-2:]}.0.{month}", country)

    params = {
        "StartDate": str(start_date),
        "EndDate": str(end_date),
        "Country": country,
        "pagesize": page_size,
    }

    next_url = ged_candidate_url(end_date.year,
                                 end_date.month) + "?" + urlencode(params)

    events = []
    while next_url != "":
        logger.info("Fetching %s", next_url)
        response = requests.get(next_url)

        try:
            assert response.status_code == 200
        except AssertionError as ae:
            raise requests.HTTPError(response=response) from ae

        data = response.json()

        try:
            events += data["Result"]
            logger.info("Retrieved %s events", len(data["Result"]))
            next_url = data["NextPageUrl"]
        except KeyError as ke:
            raise ValueError("Request returned malformed data:"
                             f"{next_url}: {str(data)}") from ke

        events = [e for e in events if not e["latitude"] is None]
        time.sleep(politeness * random.random())
    return events
Ejemplo n.º 21
0
def add_close_time(data_path, date_column="timestamp", **kwargs):
    df = pd.read_csv(data_path)
    ts = [datetime.datetime.strptime(x, "%Y-%m-%d") for x in df[date_column].values]
    ts = [t + relativedelta(**kwargs) for t in ts]

    df[date_column] = ts
    print(df.head())
    df.to_csv(data_path)
Ejemplo n.º 22
0
    def get_range(start_object=None,
                  start_object_form='%Y%m%d',
                  end_object=None,
                  end_object_form='%Y%m%d',
                  datetime_type=4):

        if start_object is None:
            raise ValueError('start_object is none')

        start_datetime = DateTimeUtil.get_object(
            src_object=start_object, src_object_form=start_object_form)

        end_datetime = DateTimeUtil.get_object(
        ) if end_object is None else DateTimeUtil.get_object(
            src_object=end_object, src_object_form=end_object_form)

        if DateTimeUtil.is_avail_date_range(start_object=start_datetime,
                                            end_object=end_datetime) is False:
            return [end_datetime]

        date_list = list()

        while True:
            if start_datetime > end_datetime:
                break

            date_list.append(start_datetime)

            if datetime_type == 1:
                start_datetime += timedelta(seconds=1)
            elif datetime_type == 2:
                start_datetime += timedelta(minutes=1)
            elif datetime_type == 3:
                start_datetime += timedelta(hours=1)
            elif datetime_type == 4:
                start_datetime += timedelta(days=1)
            elif datetime_type == 5:
                start_datetime += timedelta(weeks=1)
            elif datetime_type == 6:
                start_datetime += relativedelta(months=1)
            elif datetime_type == 7:
                start_datetime += relativedelta(years=1)
            else:
                raise TypeError("should input datetime type ")

        return date_list
Ejemplo n.º 23
0
def diff (a1,b1):
	## function calculating relative time diff between two timeFrame in sec

	differance = relativedelta(a1,b1)	
	temp = differance.years*365*24*60*60+ differance.months*30*24*60*60+differance.days*24*60*60+differance.hours*60*60+differance.minutes*60+differance.seconds
	

	return temp
Ejemplo n.º 24
0
def vtresponse():
    orderref = request.args.get('orderRef')
    slots = session['slots']
    price = session['price']
    months = session['months']
    serv = Server()
    userid = session['userid']
    user = session['username']
    openport = VoicePort.query.filter_by(port_used=2).first()
    expire = datetime.date.today() + dateutils.relativedelta(months=int(months))
    existvent = VtOrder.query.filter_by(cust_id=session['userid']).first()
    if orderref is not None and existvent is not None:
        extramonths = existvent.expiration + dateutils.relativedelta(months=int(months))
        stmt = update(VtOrder).where(VtOrder.cust_id == session['userid']).values(expiration=extramonths).values(slots=slots)
        db.session.execute(stmt)
        db.session.commit()
        #server, user, key, value
        serv.editventprops(str(ventserver.server_ip), user, str("port"), str(openport.port_no))
        serv.editventprops(str(ventserver.server_ip), user, str("maxclients"), str(slots))
        send_email('Din ordrereferanse fra Gameserver.no', ADMINS[0], session['email'],
                           render_template('receiptvt.txt', subid=str(orderref),  ordexp=str(months), slots=str(slots), totprice=session['price'], orderexp=expire),
                           render_template('receiptvt.html', subid=str(orderref), ordexp=str(months), slots=str(slots), totprice=session['price'], orderexp=expire))
        return render_template('vtresponse.html', orderref=orderref, slots=slots, price=price, months=months, ordexp=expire)
    elif orderref is not None:
        vtadd = VtOrder(slots, price, expire, openport.port_id, userid)
        stmt = update(Port).where(Port.port_id == openport.port_id).values(port_used=1)
        db.session.execute(stmt)
        db.session.add(vtadd)
        db.session.commit()
        serv.sendvent(ventserver.server_ip, user)
        serv.deployvent(user, 'ventpro.zip', ventserver.server_ip)
        serv.editventprops(str(ventserver.server_ip), user, str("port"), str(openport.port_no))
        serv.editventprops(str(ventserver.server_ip), user, str("maxclients"), str(slots))
        userstm = update(User).where(User.cust_id == session['userid']).values(role=2)
        db.session.execute(userstm)
        db.session.commit()
        session['premium'] = 2
        send_email('Din ordrereferanse fra Gameserver.no', ADMINS[0], session['email'],
                           render_template('receiptvt.txt', subid=str(orderref),  ordexp=str(months), slots=str(slots), totprice=session['price'], orderexp=expire),
                           render_template('receiptvt.html', subid=str(orderref), ordexp=str(months), slots=str(slots), totprice=session['price'], orderexp=expire))
        return render_template('vtresponse.html', orderref=orderref, slots=slots, price=price, months=months, ordexp=expire)

    else:

        return render_template('vtresponse.html', orderref=orderref, slots=slots, price=price, months=months)
Ejemplo n.º 25
0
    def yield_weight(self, trade_date):
        # 获取最近一段时间A股的波动率

        ## 取得前一个交易日的函数,在回测情况下采用历史数据

        pre_trade_date = self.data_proxy.move_trade_date(trade_date, -1)

        pre_date_str = pre_trade_date.strftime('%Y%m%d')
        start_date = pre_trade_date - dateutils.relativedelta(years=1)
        start_date_str = start_date.strftime('%Y%m%d')

        # 沪深300波动率
        # ------------------------ ------------------------
        hs300 = self.data_proxy.get_daily_quote_index('000300.SH',
                                                      start_date_str,
                                                      pre_date_str)
        hs300 = hs300[['TradeDate', 'Close']].set_index('TradeDate')
        hs_pct = hs300.pct_change().dropna()
        volatility = (hs_pct.var() * 252)['Close']

        # ------------------------ ------------------------

        # MV模型生成权重
        # 此处数据需要切换,考虑到流量的问题,采用本地化数据
        # -------------------------------- --------------------------------
        data_start_date = pre_trade_date - dateutils.relativedelta(months=3)
        data_avl = self.data_proxy.get_history_close_data(
            self.universe, data_start_date, pre_trade_date)
        data_pct = data_avl.pct_change().dropna()
        # -------------------------------- --------------------------------

        # Expected Return
        annual_ret = self.data_proxy.get_annual_ret()
        cov_mat = self.data_proxy.get_cov_mat()

        expected_ret = 0.3 * data_pct.mean() * 252 + 0.7 * annual_ret

        # Expected Covariance Matrix
        covariance_matrix = 0.3 * data_pct.cov() * 252 + 0.7 * cov_mat

        weight = optimized_weight(expected_ret,
                                  covariance_matrix,
                                  max_sigma=self.risk_level * volatility)
        return weight
Ejemplo n.º 26
0
    def get_object(src_object=None,
                   src_object_form='%Y%m%d',
                   gap=0,
                   datetime_type=4):

        if src_object is not None:

            if type(src_object) == str:
                datetime_object = datetime.strptime(src_object,
                                                    src_object_form)

            elif type(src_object) == datetime:
                datetime_object = src_object

            elif type(src_object) == date:
                datetime_object = datetime(year=src_object.year,
                                           month=src_object.month,
                                           day=src_object.day)

            else:
                datetime_object = datetime.now()

        else:
            datetime_object = datetime.now()

        if datetime_type == 1:
            datetime_object += timedelta(seconds=gap)
        elif datetime_type == 2:
            datetime_object += timedelta(minutes=gap)
        elif datetime_type == 3:
            datetime_object += timedelta(hours=gap)
        elif datetime_type == 4:
            datetime_object += timedelta(days=gap)
        elif datetime_type == 5:
            datetime_object += timedelta(weeks=gap)
        elif datetime_type == 6:
            datetime_object += relativedelta(months=gap)
        elif datetime_type == 7:
            datetime_object += relativedelta(years=gap)
        else:
            raise TypeError(
                'before type ==> sec, min, hour, day, week, month, year')

        return datetime_object
Ejemplo n.º 27
0
 def get(self, request, unit_id):
     """
     Return unit by id.
     """
     start_date = get_start_date(request)
     end_date = get_end_date(request)
     months = {}
     while(start_date <= end_date):
         first_of_month = start_date.replace(day=1)
         last_of_month = start_date.replace(
             day=1) + relativedelta(months=1) - relativedelta(days=1)
         readings_sum = MeterReading.objects.filter(
             date__gte=first_of_month,
             date__lte=last_of_month,
             unit=unit_id
         ).aggregate(Sum('usage'))
         months[start_date.strftime(
             "%Y-%m-%d")] = round(readings_sum['usage__sum']*.06, 0)
         start_date += relativedelta(months=1)
     return JsonResponse(months, safe=False)
Ejemplo n.º 28
0
 def get_context_data(self, **kwargs):
     ctx = super(ThisWeeksTransactionsListView,
                 self).get_context_data(**kwargs)
     ctx['chart_label'] = _('Previous 5 Weeks')
     ctx['period_label'] = _('This Week')
     ctx['ledgers'] = []
     for i in reversed(range(1, 6)):
         now = timezone.now()
         start = now - relativedelta(days=now.weekday() + 1, weeks=i)
         end = start + relativedelta(days=6)
         ledgers = (DailyLedger.objects.filter(created_on__range=(start,
                                                                  end),
                                               owner=self.request.user))
         ctx['ledgers'].append({
             'start':
             start.strftime('%b %d'),
             'balance':
             ledgers.aggregate(total=Sum('ending_balance'))['total'] or 0
         })
     return ctx
Ejemplo n.º 29
0
 def get_context(self, value, parent_context=None):
     ctx = super().get_context(value, parent_context=parent_context)
     weekday = ctx['value'].get('weekday')
     if weekday is not None:
         if weekday == self.PUBLIC:
             ctx['is_public'] = True
         else:
             # Next date with this weekday
             today = datetime.date.today()
             ctx['next_date'] = today + relativedelta(weekday=weekday)
     return ctx
Ejemplo n.º 30
0
 def save(self, *args, **kwargs):
     if not self.dt_expired and not self.is_permanent:
         tier = self.order.tier
         if tier.scope == 'permanent':
             self.is_permanent = True
         else:
             base_time = self.dt_created or now()
             scope_map = TIER_SCOPE_EXPIRES_MAP
             self.dt_expired = base_time + scope_map.get(
                     tier.scope, relativedelta(0))
     super(Purchase, self).save(*args, **kwargs)
Ejemplo n.º 31
0
    def get_due_date_bounds(
        self,
        timestamp: Optional[datetime] = None
    ) -> Optional[Tuple[datetime, datetime]]:
        if timestamp is None:
            timestamp = datetime.utcnow()

        if self.bill_available_day < self.bill_due_day:
            # the bill-available date and due date are within the same month, so we should file a
            # ticket if it's currently between those days this month.
            file_ticket_bounds = (
                datetime(timestamp.year, timestamp.month,
                         self.bill_available_day),
                datetime(timestamp.year, timestamp.month, self.bill_due_day),
            )
        elif self.bill_due_day < self.bill_available_day:
            # the bill due day is in a different month than when the bill is available, so things
            # are a little more complicated.

            # start looking at the current month's bill
            file_ticket_bounds = (
                datetime(timestamp.year, timestamp.month,
                         self.bill_available_day) - relativedelta(months=1),
                datetime(timestamp.year, timestamp.month, self.bill_due_day),
            )

            # but if we're already after the due date this month, look at next month
            if timestamp > file_ticket_bounds[1]:
                file_ticket_bounds = tuple(i + relativedelta(months=1)
                                           for i in file_ticket_bounds)
        else:
            raise RuntimeError(
                "Bill is available on the same day it's due, and I don't know how to handle that yet."
            )

        if (timestamp > file_ticket_bounds[0]
                and timestamp < file_ticket_bounds[1]):
            last_month = file_ticket_bounds[1] - relativedelta(months=1)
            return (last_month, file_ticket_bounds[1])

        return None
Ejemplo n.º 32
0
    def prepare(self, **kwargs):
        user = getattr(kwargs['user'], 'linked_user', None)
        if not user:
            user = getattr(kwargs['user'], 'user', None)

        # RUBIONusers or Staff without a connected website user
        # are not supported.
        if not user:
            return
            
        try:
            self.helper = NotificationSentHelper.objects.get(
                notification_id = self.identifier,
                user = user
            )
            self.helper.info = json.loads(self.helper.info)
            
        except NotificationSentHelper.DoesNotExist:
            self.helper = NotificationSentHelper(
                notification_id = self.identifier,
                user = user,
                info = {'instructions' : []}
            )

        send = False

        if self.helper.date:
            if self.helper.date < datetime.date.today() + dateutils.relativedelta(weeks = -2):
                send = True
        instruction_pks = [i['instruction'].pk for i in kwargs['instructions']]
        if not send:
            for instruction in instruction_pks:
                if instruction not in self.helper.info['instructions']:
                    send = True
                    break
        if send:
            self.helper.info['instructions'] = instruction_pks
            self.helper.save()
            language = kwargs['user'].preferred_language or 'de'
            print('Sending mail to:')
            print(kwargs['user'])
            print(kwargs['instructions'])
            self.add_mail(
                receivers = [kwargs['user'].email],
                text = self.render_template(
                    self.get_template(lang = language),
                    user = kwargs['user'],
                    si = kwargs['instructions']
                ),
                subject = self.get_subject(lang = language)
            )
Ejemplo n.º 33
0
    def expire_soon(self, soon=None):
        """Sets expiry date to be in the near future. By default expiry is
        set to token refresh margin / 2, which forces the internal middleware
        to refresh the token.

        :param int soon: Allows to specify amount of minutes in which the token
                         will expire.
        """
        soon = soon or int(settings.TOKEN_REFRESH_MARGIN / 60 / 2)
        soon = relativedelta(minutes=soon)
        exp_at = datetime.utcnow()
        if settings.USE_TZ:
            exp_at = exp_at.replace(tzinfo=pytz.utc)
        self.expires = exp_at + soon
Ejemplo n.º 34
0
def _get_or_create_household_member(survey_allocation, survey_tree):
    interviewer, survey = survey_allocation.interviewer, survey_allocation.survey
    house_number = _get_household_house_number(survey_tree)
    survey_listing = SurveyHouseholdListing.get_or_create_survey_listing(
        interviewer, survey)
    house_listing = survey_listing.listing
    try:
        household = Household.objects.get(listing=house_listing,
                                          house_number=house_number)
    except Household.DoesNotExist:
        physical_addr = ''
        try:
            physical_addr = _get_household_physical_addr(survey_tree)
        except IndexError:
            pass
        household = Household.objects.create(
            last_registrar=interviewer,
            listing=house_listing,
            registration_channel=ODKAccess.choice_name(),
            house_number=house_number,
            physical_address=physical_addr)
    #now time for member details
    MALE = '1'
    IS_HEAD = '1'
    mem_attrs = _get_member_attrs(survey_tree)
    kwargs = {}
    kwargs['surname'] = mem_attrs.get('surname')
    kwargs['first_name'] = mem_attrs['firstName']
    kwargs['gender'] = (mem_attrs['sex'] == MALE)
    date_of_birth = current_val = datetime.now() - relativedelta(
        years=int(mem_attrs['age']))
    kwargs['date_of_birth'] = date_of_birth
    #datetime.strptime(mem_attrs['dateOfBirth'], '%Y-%m-%d')
    kwargs['household'] = household
    kwargs['registrar'] = interviewer
    kwargs['registration_channel'] = ODKAccess.choice_name()
    kwargs['survey_listing'] = survey_listing
    if not household.get_head() and mem_attrs['isHead'] == IS_HEAD:
        # kwargs['occupation'] = mem_attrs.get('occupation', '')
        # kwargs['level_of_education'] = mem_attrs.get('levelOfEducation', '')
        # resident_since = datetime.strptime(mem_attrs.get('residentSince', '1900-01-01'), '%Y-%m-%d')
        # kwargs['resident_since']=resident_since
        head = HouseholdHead.objects.create(**kwargs)
        if household.head_desc is not head.surname:
            household.head_desc = head.surname
            household.save()
        return head
    else:
        return HouseholdMember.objects.create(**kwargs)
Ejemplo n.º 35
0
def test_genrange_datetime():
    begin = datetime.strptime("2008010112", "%Y%m%d%H")
    end = datetime.strptime("2008010512", "%Y%m%d%H")

    interval, units = "1 day".split()
    if not units.endswith('s'):
        units = units + 's'
    delta = relativedelta(**dict([[units, int(interval)]]))

    assert (list(utils.genrange(begin, end, delta)) == [
        datetime(2008, 1, 1, 12, 0),
        datetime(2008, 1, 2, 12, 0),
        datetime(2008, 1, 3, 12, 0),
        datetime(2008, 1, 4, 12, 0)
    ])
Ejemplo n.º 36
0
def date_dictionary(apps, schema_editor):
    DateDictionary = apps.get_model("import_etl", "DateDictionary")
    start_date = datetime.date(2010, 1, 1)
    end_date = datetime.date(2025, 12, 31)

    while start_date <= end_date:
        dt = DateDictionary(
            src_id=start_date,
            year=start_date.year,
            month=start_date.month,
            day_of_the_month=start_date.day,
            quarter_of_the_year=int((start_date.month-1) / 3) + 1,
            half_of_the_year=int((start_date.month-1)/6) + 1
        )
        dt.save(force_insert=True)
        start_date = start_date + relativedelta(days=1)
Ejemplo n.º 37
0
 def finalize(self, request):
     parent = self.get_parent()
     project = self.make_project()
     project = parent.add_child(instance = project)
     self.make_relations(project)
     # Setting status of project
     if self.session_store['status']['form']['status'] == 'accepted':
         now = datetime.datetime.now()
         next_year = now + relativedelta(years=+1)
         project.expire_at = next_year
         project.go_live_at = now
         revision = project.save_revision(user=request.user)
         revision.publish()
     if self.session_store['status']['form']['status'] == 'applied':
         project.save_revision(user=request.user, submitted_for_moderation = True)
     return redirect('rai_userinput_project_edit', pk = project.pk)
Ejemplo n.º 38
0
    def handle(self, *args, **options):
        base_url = 'http://%s/en' % options['host']
        cli = HTMLSession()

        # Login as manager
        res = cli.post(base_url + '/accounts/login/',
                       data={
                           'username':
                           options['username'],
                           'password':
                           options['password'],
                           'csrfmiddlewaretoken':
                           Command._get_csrf_token(
                               cli, base_url + '/accounts/login/')
                       })
        if res.status_code != 200:
            raise RuntimeError('Could not login (status %d)' % res.status_code)

        # Get report HTML
        end_date = datetime.today().replace(day=1) - relativedelta(days=1)
        start_date = end_date.replace(day=1)
        res = cli.post(base_url + '/events/report/',
                       data={
                           'start_date':
                           start_date.strftime('%Y-%m-%d'),
                           'end_date':
                           end_date.strftime('%Y-%m-%d'),
                           'include':
                           Command.include,
                           'csrfmiddlewaretoken':
                           Command._get_csrf_token(
                               cli, base_url + '/events/report/')
                       })
        if res.status_code != 200:
            raise RuntimeError('Could not get report (status %d)' %
                               res.status_code)

        res.html.render(reload=False)
        result = open('output.pdf', 'w+b')
        status = pisa.CreatePDF(res.html.find('.container',
                                              first=True).raw_html,
                                dest=result)
        result.close()
        cli.close()
        if status.err:
            raise RuntimeError('PDF did not process correctly')
        logger.info("Successfully generated PDF")
Ejemplo n.º 39
0
def _get_or_create_household_member(interviewer, survey, survey_tree):
    house_number = _get_household_house_number(survey_tree)
    survey_listing = SurveyHouseholdListing.get_or_create_survey_listing(interviewer, survey)
    house_listing = survey_listing.listing
    try:
        household = Household.objects.get(listing=house_listing, house_number=house_number)
    except Household.DoesNotExist:
        physical_addr = ""
        try:
            physical_addr = _get_household_physical_addr(survey_tree)
        except IndexError:
            pass
        household = Household.objects.create(
            last_registrar=interviewer,
            listing=house_listing,
            registration_channel=ODKAccess.choice_name(),
            house_number=house_number,
            physical_address=physical_addr,
        )
    # now time for member details
    MALE = "1"
    IS_HEAD = "1"
    mem_attrs = _get_member_attrs(survey_tree)
    kwargs = {}
    kwargs["surname"] = mem_attrs.get("surname")
    kwargs["first_name"] = mem_attrs["firstName"]
    kwargs["gender"] = mem_attrs["sex"] == MALE
    date_of_birth = current_val = datetime.now() - relativedelta(years=int(mem_attrs["age"]))
    kwargs["date_of_birth"] = date_of_birth
    # datetime.strptime(mem_attrs['dateOfBirth'], '%Y-%m-%d')
    kwargs["household"] = household
    kwargs["registrar"] = interviewer
    kwargs["registration_channel"] = ODKAccess.choice_name()
    kwargs["survey_listing"] = survey_listing
    if not household.get_head() and mem_attrs["isHead"] == IS_HEAD:
        # kwargs['occupation'] = mem_attrs.get('occupation', '')
        # kwargs['level_of_education'] = mem_attrs.get('levelOfEducation', '')
        # resident_since = datetime.strptime(mem_attrs.get('residentSince', '1900-01-01'), '%Y-%m-%d')
        # kwargs['resident_since']=resident_since
        head = HouseholdHead.objects.create(**kwargs)
        if household.head_desc is not head.surname:
            household.head_desc = head.surname
            household.save()
        return head
    else:
        return HouseholdMember.objects.create(**kwargs)
Ejemplo n.º 40
0
    def get(self, request, reset_token, *args, **kwargs):
        # fetch token if it's timestamp is shorter than 24hrs
        hrs24 = datetime.now() - relativedelta(hours=24)
        try:
            token_data = PasswordResetToken.objects.get(pk=reset_token,
                                                        timestamp__gte=hrs24)
        except PasswordResetToken.DoesNotExist:
            messages.error(self.request,
                           _("The reset password token is either expired or "
                             "has been already used once. Please use reset "
                             "password again."))
            return HttpResponseRedirect(reverse('reset_password'))

        users = json.loads(token_data.data)
        if len(users) > 1 and not kwargs.get('idMember'):
            # there are more than one possible accounts for password reset
            # and the request did not go through select address view,
            # get the list of addresses out of list of Persons
            members = list()
            for user in users:
                member = user['member']
                member['fullAddress'] = user['address']['fullAddress']
                member['idUser'] = user['idUser']
                members.append(member)

            kwargs['page_title'] = _("Please select an Address for password"
                                     " reset.")
            kwargs['target'] = reverse("reset_password_confirm",
                                       kwargs={'reset_token': reset_token})
            select_member_view = SelectMember(request=request, args=args,
                                              kwargs=kwargs)
            return select_member_view.get(request, *args, members=members,
                                          **kwargs)
        elif kwargs.get('idMember'):
            user = token_data.get_user_for_member(kwargs['idMember'])
            if not user:
                messages.error(request, _("Could not identify the User. "
                                          "Please try to use reset password "
                                          "again."))
                return HttpResponseRedirect(reverse('reset_password'))
            self.initial['idUser'] = user['idUser']
        else:
            self.initial['idUser'] = users[0]['idUser']
        return super(ResetPasswordConfirm, self).get(request, *args, **kwargs)
Ejemplo n.º 41
0
    def get_project_context(self):
        months = []
        projectcounts = []
        eprojectcounts = []
        iprojectcounts = []

        for m in range(24, -1, -1):
            d = self.today - relativedelta(months=m, day=1)
            months.append('\'{m}/{y}\''.format(m=d.month, y=d.year))
            projectcounts.append(
                Project.objects.filter(
                    Q(first_published_at__lte=d)
                    & (Q(expire_at__gte=d)
                       | Q(expire_at=None))).live().count())

        return {
            'months': mark_safe(','.join(months)),
            'projectcounts': projectcounts
        }
Ejemplo n.º 42
0
    def signs_per_month_plot(self):
        signs_per_month_data = self.domain_query(
            func.strftime('%Y-%m', Signature.sign_date).label('sign_month'),
            func.COUNT(Signature.id).label('num_sigs')).join(Key).filter(
                Signature.sign_date > date.today() -
                relativedelta(years=2)).group_by('sign_month').order_by(
                    asc('sign_month')).all()

        data = dict(signs=[sig.num_sigs for sig in signs_per_month_data],
                    months=[sig.sign_month for sig in signs_per_month_data])

        b = Bar(data,
                values='signs',
                label='months',
                plot_width=800,
                legend=False,
                color='#0275d8')

        return components(b)
Ejemplo n.º 43
0
    def calendar(self):
        """
        Renders the view as a list of months.
        """
        if len(self.days) == 0:
            raise ValueError('Calendar rendering is not permitted without '
                             'events.')
        cal = Calendar()
        months = []
        remaining_days = sorted([k for k in self.days.keys()])
        current_day = remaining_days[0].replace(day=1)
        remaining_events = len(self.events)
        while remaining_events > 0:
            month = cal.monthdatescalendar(current_day.year, current_day.month)
            month_view = []
            for i, month_week in enumerate(month):
                month_view.append([])
                for j, day in enumerate(month_week):
                    if day.weekday() not in [5, 6]:  # weekend removal
                        month_view[i].append([])
                        if day in self.days:
                            events, daily_events_count = \
                                self._extract_day_events(day)
                            events = copy.deepcopy(events)
                            events.add_attributes({
                                'cur_month': day.month == current_day.month,
                            })
                            remaining_events -= daily_events_count
                            month_view[i][j] = events
                        else:

                            default_attributes = {
                                'active': False,
                                'today': day == date.today(),
                                'cur_month': day.month == current_day.month
                            }
                            month_view[i][j] = EventDay(
                                day,
                                attributes=default_attributes)
            months.append({'month': current_day,
                           'dates': month_view})
            current_day = current_day + relativedelta(months=1)
        return months
Ejemplo n.º 44
0
def get_monthly_totals():
    earliest_transaction_date = \
        models.Transaction.objects.order_by('date')[0].date
    months = []
    date = earliest_transaction_date
    while True:
        months_transactions = models.Transaction.objects.filter(
            date__month=date.month,
            date__year=date.year)
        if not months_transactions.count():
            break
        months.append(
            (
                datetime.date(date.year, date.month, 1),
                months_transactions.exclude(
                    tags__name__in=['transfer', 'interest', "mums's loan"]
                ).aggregate(sum=Sum('amount'))
                )
            )
        date += relativedelta(months=1)
    months.reverse()
    return months
Ejemplo n.º 45
0
def format_timedelta(target):
	now = datetime.datetime.now()
	difference = relativedelta(now, target)
	if difference.years > 0:
		if difference.years == 1:
			return "1 year ago"
		else:
			return str(difference.years) + " years ago"
	elif difference.months > 0:
		if difference.months == 1:
			return "1 month ago"
		else:
			return str(difference.months) + " months ago"
	elif difference.days > 0:
		if difference.days == 1:
			return "Yesterday"
		elif difference.days > 6:
			weeks = difference.days/7
			if weeks == 1:
				return "1 week ago"
			else:
				return str(weeks) + " weeks ago"
		else:
			return str(difference.days) + " days ago"
	elif difference.hours >0:
		if difference.hours == 1:
			return "1 hour ago"
		else:
			return str(difference.hours) + " hours ago"

	elif difference.minutes >0:
		if difference.minutes < 5:
			return "Just now"
		else:
			return str(difference.minutes) + " minutes ago"

	else: 
		return "Just now"
Ejemplo n.º 46
0
    def calendar(self):
        """generates calendars representing all meals in the session, as a list
        of Calendar.monthdatescalendar() lists.
        In those lists, the second values of tuples are the corresponding Meal
        objects.
        """
        cur_month = None

        meals = self.meal_set.order_by('date')
        meals_dates = {}
        meals_count = 0
        for meal in meals:
            cur_month = meal.date if cur_month is None else cur_month
            meals_count += 1
            if meal.date not in meals_dates:
                if meal.date.date() not in meals_dates:
                    meals_dates[meal.date.date()] = []
            meals_dates[meal.date.date()].append(meal)

        if not cur_month:
            cur_month = datetime.now()

        months = []

        cal = Calendar()
        month = cal.monthdatescalendar(cur_month.year, cur_month.month)
        remaining_meals = meals_count
        while remaining_meals > 0:
            month = cal.monthdatescalendar(cur_month.year, cur_month.month)
            for i, month_week in enumerate(month):
                for j, day in enumerate(month_week):
                    meal_dates = meals_dates[day] if day in meals_dates and \
                        day.month == cur_month.month else []
                    remaining_meals -= len(meal_dates)
                    month[i][j] = {'date': month[i][j], 'meals': meal_dates}
            months.append({'month': cur_month, 'dates': month})
            cur_month = cur_month + relativedelta(months=1)
        return months
Ejemplo n.º 47
0
def prepare_datetime(dt):
    months = {
        'янв.': 1, 'фев.': 2, 'мар.': 3,
        'апр.': 4, 'мая': 5, 'июн.': 6,
        'июл.': 7, 'авг.': 8, 'сен.': 9,
        'окт.': 10, 'нояб.': 11, 'дек.': 12
    }

    dt = normalize_string(dt)
    date_parts = dt.split(" ")

    today = date.today()
    if date_parts[0] == 'Сегодня':
        d = today
    elif date_parts[0] == 'Вчера':
        d = today - timedelta(days=1)
    else:
        day = int(date_parts[0])
        month = int(months[date_parts[1]])
        d = date(today.year, month, day)
        if d > today:
            d -= relativedelta(years=1)

    return d
Ejemplo n.º 48
0
    def authenticate(self, request=None, username=None, password=None,
                     user_domain_name=None, auth_url=None, idMember=None,
                     token_id=None, scope=None):
        """Authenticates user against CIX Session Service

        :param username: CIX username
        :type username: str | unicode
        :param password: CIX password
        :type password: str | unicode
        :param idMember: in case of multi-account users - idMember, optional
        :type idMember: int | str | unicode | None
        :returns: User object
        :rtype: cix.django_plugin.models.django_auth.User | None
        """
        LOG.debug('Beginning user authentication for user "%s".' % username)

        if auth_url is None:
            auth_url = settings.OPENSTACK_KEYSTONE_URL
        kw = {
            'username': username,
            'password': password,
            'token_id': token_id,
            'idMember': idMember,
            'scope': scope
        }
        kw = dict(filter(lambda o: o if o[1] else None, kw.items()))
        if 'token_id' in kw.keys():
            kw.pop('username', '')
            kw.pop('password', '')
        else:
            kw.pop('token_id', '')
        # Create the session for a user.
        auth = utils.CloudCIXAuth(auth_url=auth_url, **kw)
        session = utils.KeystoneSession(auth=auth)
        try:
            unscoped_auth_ref = auth.get_access(session)
        except keystone_exceptions.Unauthorized as exc:
            if getattr(session.auth, 'additional_auth_required', None):
                raise AdditionalAuthRequired(session)
            msg = _('Invalid credentials.')
            LOG.debug(str(exc))
            raise exceptions.KeystoneAuthException(msg)
        except (keystone_exceptions.Forbidden,
                keystone_exceptions.NotFound) as exc:
            msg = _('Invalid credentials.')
            LOG.debug(str(exc))
            raise exceptions.KeystoneAuthException(msg)
        except (keystone_exceptions.ClientException,
                keystone_exceptions.AuthorizationFailure) as exc:
            msg = _("An error occurred authenticating. "
                    "Please try again later.")
            LOG.debug(str(exc))
            raise exceptions.KeystoneAuthException(msg)

        # Create a trust from the user to the api user for the session time
        # (max 24hrs) and issue a new token based on the issued trust
        admin_session = utils.get_admin_session()
        admin_token = admin_session.auth.get_access(admin_session)
        keystone = keystone_v3.Client(session=session,
                                      auth_url=auth_url,
                                      endpoint_override=auth_url)
        trust = keystone.trusts.create(
            trustee_user=admin_token['user']['id'],
            trustor_user=unscoped_auth_ref['user']['id'],
            impersonation=True,
            allow_redelegation=True,
            expires_at=datetime.utcnow() + relativedelta(
                hours=getattr(settings, 'HORIZON_SESSION_LENGTH', 24)))
        admin_session = utils.get_admin_session(
            private_session=True,
            scope={"OS-TRUST:trust": {"id": trust.id}})
        unscoped_auth_ref = admin_session.auth.get_access(session)
        return self._process_auth_ref(request, unscoped_auth_ref, auth_url)
Ejemplo n.º 49
0
 def age(self):
     return dateutils.relativedelta(datetime.utcnow().date(), self.date_of_birth).years
    def __call__(self):
        account = get_account(self.account_name)

        data = dict(purchases=[], dividend=[], value=[])

        last_dividend = Decimal('0.0')
        last_purchase = Decimal('0.0')

        currency = get_currency()

        purchases = dict()
        dividends = dict()
        values = dict()

        for split in account.GetSplitList():
            other_account_name = get_corr_account_full_name(split)
            other_account = get_account(other_account_name)

            account_type = AccountTypes(other_account.GetType())
            date = datetime.fromtimestamp(split.parent.GetDate())

            # Store previous data
            if len(purchases):
                previous_date = date - relativedelta(days=1)
                previous_date_key = time.mktime(previous_date.timetuple())
                purchases[previous_date_key] = last_purchase
                dividends[previous_date_key] = last_dividend
                values[previous_date_key] = get_balance_on_date(account, previous_date, currency)

            # Find the correct amount that was paid from the account into this account.
            change_amount = get_decimal(split.GetValue())

            if change_amount > 0:
                # Need to get the value from the corr account split.
                for parent_splits in split.parent.GetSplitList():
                    if parent_splits.GetAccount().get_full_name() == other_account_name:
                        change_amount = -get_decimal(parent_splits.GetValue())

            if account_type == AccountTypes.mutual_fund or account_type == AccountTypes.asset:
                # Asset or mutual fund transfer
                last_purchase += change_amount
            else:
                last_dividend += get_decimal(split.GetValue())

            key = time.mktime(date.timetuple())
            purchases[key] = last_purchase
            dividends[key] = last_dividend
            values[key] = get_balance_on_date(account, date, currency)

        # Now get all of the price updates in the database.
        price_database = get_session().get_book().get_price_db()
        commodity = account.GetCommodity()
        for price in price_database.get_prices(commodity, None):
            date = time.mktime(price.get_time().timetuple())

            values[date] = max(values.get(date, Decimal('0.0')),
                               get_balance_on_date(account, price.get_time(), currency))

        data['purchases'] = sorted([(key, value) for key, value in purchases.iteritems()], key=itemgetter(0))
        data['dividend'] = sorted([(key, value) for key, value in dividends.iteritems()], key=itemgetter(0))
        data['value'] = sorted([(key, value) for key, value in values.iteritems()], key=itemgetter(0))

        results = self._generate_result()
        results['data'] = data

        return results
Ejemplo n.º 51
0
def mdateutil():
    startdate_struct=time.strptime('20150923','%Y%m%d')  #time.struct_time
    start_date=date(startdate_struct.tm_year,startdate_struct.tm_mon,startdate_struct.tm_mday)  #datetime.date
    now_date=datetime.date(datetime.now())  #date
    daydiff=relativedelta(now_date,start_date) # 参数是两个日期类型,返回是差的日期数:relativedelta(months=+2, days=+22)
    print(daydiff)
Ejemplo n.º 52
0
    def form_valid(self, form):
        token = get_admin_session().get_token()
        cd = form.cleaned_data
        member_data = {
            'groupName': cd['companyName'],
            'idCurrency': 1
        }
        response = api.membership.member.create(token=token, data=member_data)
        if response.status_code != 201:
            for field, err in response.json()['errors'].items():
                if field in form.fields:
                    form.add_error(field, err[0]['message'])

        addr_data = {
            'companyName': cd['companyName'],
            'idCurrency': 1,
            'idLanguage': 1,
            'idCountry': cd['idCountry'],
            'city': cd['city'],
            'address1': cd['address1'],
            'address2': cd['address2'],
            'address3': cd['address3'],
            'idMember': response.json().get('content', dict()).get(
                'idMember', None)
        }
        response = api.membership.address.create(token=token, data=addr_data)
        if response.status_code != 201:
            for field, err in response.json()['errors'].items():
                if field in form.fields:
                    form.add_error(field, err[0]['message'])

        user_data = {
            'username': cd['username'],
            'password': cd['password'],
            'idAddress': response.json().get('content', dict()).get(
                'idAddress', None),
            'idLanguage': 1,
            'firstName': cd['firstName'],
            'surname': cd['surname'],
            'timezone': 'UTC',
            'startDate': datetime.utcnow().date().isoformat(),
            'expiryDate': (datetime.utcnow() +
                           relativedelta(years=1)).date().isoformat()
        }
        response = api.membership.user.create(token=token, data=user_data)
        if response.status_code != 201:
            for field, err in response.json()['errors'].items():
                if field in form.fields:
                    form.add_error(field, err[0]['message'])

        if form.errors:
            return self.form_invalid(form)

        api.membership.member.partial_update(
            pk=addr_data['idMember'],
            token=token,
            data={'selfManaged': True})
        messages.success(self.request, _('Your account has been successfully '
                                         'created. You can now login.'))

        return super(Register, self).form_valid(form)
    def get_interview_answers(self):
        report = []
        member_reports = OrderedDict()
        val_list_args = [  'interview__ea__locations__name',
                         'interview__ea__name', 'interview__householdmember__household__house_number',
                         'interview__householdmember__surname', 'interview__householdmember__first_name',
                         'interview__householdmember__date_of_birth', 'interview__householdmember__gender', ]
        parent_loc = 'interview__ea__locations'
        for i in range(LocationType.objects.count() - 2):
            parent_loc = '%s__parent' % parent_loc
            val_list_args.insert(0, '%s__name'%parent_loc)
        filter_args = {}
        if self.locations:
            filter_args['interview__ea__locations__in'] = self.locations
        if self.specific_households:
            filter_args['interview__householdmember__household__in'] = self.specific_households
        for answer_type in Answer.answer_types():
            query_args = list(val_list_args)
            value = 'value'
            if answer_type in [MultiChoiceAnswer.choice_name(), ]:
                value = 'value__order'
                if  self.multi_display == self.AS_LABEL:
                    value = 'value__order'
                else:
                    value = 'value__text'
            query_args.append(value)
            answer_class = Answer.get_class(answer_type)
            # print 'using query_args ', query_args
            answer_data = answer_class.objects.filter(interview__batch=self.batch, **filter_args).\
                values_list('interview__householdmember__pk', 'question__pk', *query_args).\
                        order_by('interview__ea__locations', 'interview__ea',
                                 'interview__householdmember__household').distinct(
                                                                            'interview__ea__locations',
                                                                            'interview__ea',
                                                                            'interview__householdmember__household',
                                                                            'interview__householdmember__pk',
                                                                            'question__pk'
                                                                            )
            answer_data = list(answer_data)
            # print 'answer data ', len(answer_data)
            #now grab member reports
            for data in answer_data:
                hm_pk, question_pk = data[:2]
                report_data = list(data[2:])
                hm_data = member_reports.get(hm_pk, None)
                if hm_data is None:
                    report_data.insert(-3, str(dateutils.relativedelta(datetime.utcnow().date(),
                                                                       report_data[-3]).years))
                    report_data[-3] = report_data[-3].strftime(settings.DATE_FORMAT)
                    report_data[-2] = 'M' if report_data[-2] else 'F'
                    member_details = [ unicode(md).encode('utf8') for md in report_data[:-1]]
                    hm_data = OrderedDict([('mem_details' , member_details), ])
                hm_data[question_pk] =  unicode(report_data[-1]).encode('utf8')
                member_reports[hm_pk] = hm_data

        for hm in member_reports.values():
            answers = hm['mem_details']
            for question in self.questions:
                answers.append(hm.get(question.pk, ''))
            report.append(answers)
        return report
Ejemplo n.º 54
0
	def updateCurrent(self):
		if "%B" in self.scrapePattern.archLink_fmt:
			self.current += relativedelta(months=1)
		else:
			self.current += relativedelta(years=1)