Based on the period, date and evolution_{$period}_last_n query parameters,
calculates the date range this evolution chart will display data for.
486242
private function calculateEvolutionDateRange()
    {
        $period = Common::getRequestVar('period');
        $idSite = Common::getRequestVar('idSite');
        $timezone = Site::getTimezoneFor($idSite);

        $defaultLastN = self::getDefaultLastN($period);
        $originalDate = Common::getRequestVar('date', 'last' . $defaultLastN, 'string');

        if ('range' != $period) { // show evolution limit if the period is not a range
            // set the evolution_{$period}_last_n query param
            if (Range::parseDateRange($originalDate)) {
                // if a multiple period

                // overwrite last_n param using the date range
                $oPeriod = new Range($period, $originalDate, $timezone);
                $lastN   = count($oPeriod->getSubperiods());

            } else {
                // if not a multiple period
                list($newDate, $lastN) = self::getDateRangeAndLastN($period, $originalDate, $defaultLastN);
                $this->requestConfig->request_parameters_to_modify['date'] = $newDate;
                $this->config->custom_parameters['dateUsedInGraph'] = $newDate;
            }

            $lastNParamName = self::getLastNParamName($period);
            $this->config->custom_parameters[$lastNParamName] = $lastN;
        }
    }
860644
def daterange_end(value):
    ''''''
    if not value:
        return None
    elif isinstance(value, datetime):
        return value.date()
    elif isinstance(value, date):
        return value

    result = parse_dt(value).date()
    dashes = value.count('-')

    if dashes >= 2:
        # Full date
        return result
    elif dashes == 1:
        # Year/Month
        return result + relativedelta(months=+1, days=-1, day=1)
    else:
        # Year only
        return result.replace(month=12, day=31)
988969
def top_pages_by_time_period(self, interval='day'):
        
        date_trunc = fn.date_trunc(interval, PageView.timestamp)
        return (self.get_query()
                .select(
                    PageView.url,
                    date_trunc.alias(interval),
                    fn.Count(PageView.id).alias('count'))
                .group_by(PageView.url, date_trunc)
                .order_by(
                    SQL(interval),
                    SQL('count').desc(),
                    PageView.url))
997501
def range

      now = Time.now

      [ (Time.parse(@history.first['seen_at']) rescue now),
        (Time.parse(@history.last['seen_at']) rescue now) ]
    end
207791
public function scopeWithinPeriod(Builder $query, Period $period)
    {
        $startDateTime = $period->getStartDateTime();
        $endDateTime = $period->getEndDateTime();

        if ($startDateTime && ! $endDateTime) {
            $query->where('viewed_at', '>=', $startDateTime);
        } elseif (! $startDateTime && $endDateTime) {
            $query->where('viewed_at', '<=', $endDateTime);
        } elseif ($startDateTime && $endDateTime) {
            $query->whereBetween('viewed_at', [$startDateTime, $endDateTime]);
        }

        return $query;
    }
1202218
def GetDateRange(self):
    
    (minvalue, maxvalue, minorigin, maxorigin) = self.GetDateRangeWithOrigins()
    return (minvalue, maxvalue)
890269
def set_range(self, start=None, end=None, occurrences=None):
        
        if start is None:
            if self.__start_date is None:
                self.__start_date = dt.date.today()
        else:
            self.start_date = start

        if end:
            self.end_date = end
        elif occurrences:
            self.__occurrences = occurrences
        self._track_changes()
23325
public static function getDatesForPeriod($period)
    {
        /*
         * Type of period is incorrect?
         * Nothing to do
         */
        if (!(new DatePeriod())->isCorrectType($period)) {
            return null;
        }

        $dateStart = null;
        $dateEnd = null;

        switch ($period) {
            case DatePeriod::LAST_WEEK:
                $thisWeekStart = new DateTime('this week');

                $dateStart = clone $thisWeekStart;
                $dateEnd = clone $thisWeekStart;

                $dateStart->sub(new DateInterval('P7D'));
                $dateEnd->sub(new DateInterval('P1D'));

                break;
            case DatePeriod::THIS_WEEK:
                $dateStart = new DateTime('this week');

                $dateEnd = clone $dateStart;
                $dateEnd->add(new DateInterval('P6D'));

                break;
            case DatePeriod::NEXT_WEEK:
                $dateStart = new DateTime('this week');
                $dateStart->add(new DateInterval('P7D'));

                $dateEnd = clone $dateStart;
                $dateEnd->add(new DateInterval('P6D'));

                break;
            case DatePeriod::LAST_MONTH:
                $dateStart = new DateTime('first day of last month');
                $dateEnd = new DateTime('last day of last month');

                break;
            case DatePeriod::THIS_MONTH:
                $lastMonth = self::getDatesForPeriod(DatePeriod::LAST_MONTH);
                $nextMonth = self::getDatesForPeriod(DatePeriod::NEXT_MONTH);

                if (null !== $lastMonth) {
                    $dateStart = $lastMonth->getEndDate();
                    $dateStart->add(new DateInterval('P1D'));
                }

                if (null !== $nextMonth) {
                    $dateEnd = $nextMonth->getStartDate();
                    $dateEnd->sub(new DateInterval('P1D'));
                }

                break;
            case DatePeriod::NEXT_MONTH:
                $dateStart = new DateTime('first day of next month');
                $dateEnd = new DateTime('last day of next month');

                break;
            case DatePeriod::LAST_YEAR:
            case DatePeriod::THIS_YEAR:
            case DatePeriod::NEXT_YEAR:
                $dateStart = new DateTime();
                $dateEnd = new DateTime();

                $yearPeriod = [
                    DatePeriod::LAST_YEAR,
                    DatePeriod::NEXT_YEAR,
                ];

                if (in_array($period, $yearPeriod, true)) {
                    $yearDifference = 1;

                    if (DatePeriod::LAST_YEAR === $period) {
                        $yearDifference *= -1;
                    }

                    $modifyString = sprintf('%s year', $yearDifference);
                    $dateStart->modify($modifyString);
                    $dateEnd->modify($modifyString);
                }

                $year = $dateStart->format('Y');
                $dateStart->setDate($year, 1, 1);
                $dateEnd->setDate($year, 12, 31);

                break;
        }

        /*
         * Start or end date is unknown?
         * Nothing to do
         */
        if (null === $dateStart || null === $dateEnd) {
            return null;
        }

        $dateStart->setTime(0, 0);
        $dateEnd->setTime(23, 59, 59);

        return new DatePeriod($dateStart, $dateEnd);
    }
224496
public static function lastQuarterLastSecond()
    {
        $season = ceil((date('n')) / 3) - 1;
        return mktime(23, 59, 59, $season * 3, date('t', mktime(0, 0, 0, $season * 3, 1, date("Y"))), date('Y'));
    }
270309
def daterange(start, end, delta=timedelta(days=1), lower=Interval.CLOSED, upper=Interval.OPEN):
    """"""
    date_interval = Interval(lower=lower, lower_value=start, upper_value=end, upper=upper)
    current = start if start in date_interval else start + delta
    while current in date_interval:
        yield current
        current = current + delta
680198
function aggregateMetrics(currentTime, metricData) {
    var aggregateKey;

    /**
     * Place aggregate data into the specified slot.  If the current zoom
     * level matches the aggregate level, the data is emitted to keep the
     * display in sync.
     *
     * @param {Number} index
     * The desired slot for the aggregate.
     *
     * @param {Object} data
     * The aggregate data.
     *
     * @returns {void}
     */
    var setAggregateData =
      function setAggregateData(index, data) {
        this._aggregation[aggregateKey].data[index] = data;

        // if this view (current or not) is scrolled, adjust it
        if (this._aggregation[aggregateKey].scrollOffset) {
          this._aggregation[aggregateKey].scrollOffset--;
        }

        // emit to keep the display in sync
        if (this.isCurrentZoom(aggregateKey)) {
          if (this.isScrolled()) {
            this.emit("refreshMetrics");
          } else {
            this.emit("metrics", data);
          }
        }
      }.bind(this);

    /**
     * Given the current time time index, add any missing logical
     * time slots to have a complete picture of data.
     *
     * @param {Number} currentTimeIndex
     * The time index currently being processed.
     *
     * @returns {void}
     */
    var addMissingTimeSlots =
      function addMissingTimeSlots(currentTimeIndex) {
        var aggregateIndex = this._aggregation[aggregateKey].data.length;
        while (aggregateIndex < currentTimeIndex) {
          setAggregateData(aggregateIndex++, this.emptyAverage);
        }
      }.bind(this);

    /**
     * After having detected a new sampling, aggregate the relevant data points
     *
     * @param {Object[]} rows
     * The array reference.
     *
     * @param {Number} startIndex
     * The starting index to derive an average.
     *
     * @param {Number} endIndex
     * The ending index to derive an average.
     *
     * @returns {void}
     */
    var getAveragedAggregate =
      function getAveragedAggregate(rows, startIndex, endIndex) {
        var averagedAggregate = getInitializedAverage(metricData);

        // this is the number of elements we will aggregate
        var aggregateCount = endIndex - startIndex + 1;

        // you can compute an average of a set of numbers two ways
        // first, you can add all the numbers together and then divide by the count
        // second, you call divide each number by the count and add the quotients
        // the first method is more accurate, however you can overflow an accumulator
        // and result with NaN
        // the second method is employed here to ensure no overflows

        for (var dataKey in metricData) {
          for (var dataMetricKey in metricData[dataKey]) {
            for (var rowIndex = startIndex; rowIndex <= endIndex; rowIndex++) {
              averagedAggregate[dataKey][dataMetricKey] +=
                rows[rowIndex][dataKey][dataMetricKey] / aggregateCount;
            }

            // after the average is done, truncate the averages to one decimal point
            averagedAggregate[dataKey][dataMetricKey] =
              +averagedAggregate[dataKey][dataMetricKey].toFixed(1);
          }
        }

        return averagedAggregate;
      };

    /**
     * Process one row of metric data into aggregate.
     *
     * @param {Number} rowIndex
     * The index of the row being processed.
     *
     * @param {Object[]} rows
     * The array reference.
     *
     * @returns {void}
     */
    var processRow = function processRow(rowIndex, rows) {
      var averagedAggregate;
      var lastTimeIndex = this._aggregation[aggregateKey].lastTimeIndex;

      // get the time index of the aggregate
      var currentTimeIndex =
        convertElapsedTimeToTimeIndex(currentTime, this._startTime, +aggregateKey);

      // when the time index changes, average the data for the time band
      if (currentTimeIndex !== lastTimeIndex) {
        // except for the first one
        if (lastTimeIndex !== undefined) {
          // add in any missing logical time slots
          addMissingTimeSlots.call(this, lastTimeIndex);

          // get the average across the discovered time band
          averagedAggregate = getAveragedAggregate(
            rows,
            this._aggregation[aggregateKey].lastAggregateIndex,
            rowIndex - 1
          );

          // place the average
          setAggregateData(lastTimeIndex, averagedAggregate);

          // now we know where the next aggregate begins
          this._aggregation[aggregateKey].lastAggregateIndex = rowIndex;
        }

        // level-break
        this._aggregation[aggregateKey].lastTimeIndex = currentTimeIndex;
      }
    }.bind(this);

    // iterate over the configured aggregation time buckets
    for (aggregateKey in this._aggregation) {
      // iterate through metrics, beginning where we left off
      processRow(this._lastAggregationIndex, this._metrics);
    }

    // remember where we will begin again
    this._lastAggregationIndex++;
  }
1218578
def last_quarter():
        
        since, until = Date.this_quarter()
        since = since.date - delta(months=3)
        until = until.date - delta(months=3)
        return Date(since), Date(until)
455735
def daterange_with_details(value):
    ''''''
    delta = value.end - value.start
    start, end = None, None
    if is_first_year_day(value.start) and is_last_year_day(value.end):
        start = value.start.year
        if delta.days > 365:
            end = value.end.year
    elif is_first_month_day(value.start) and is_last_month_day(value.end):
        start = short_month(value.start)
        if delta.days > 31:
            end = short_month(value.end)
    else:
        start = short_day(value.start)
        if value.start != value.end:
            end = short_day(value.end)
    return _('%(start)s to %(end)s', start=start, end=end) if end else start
1087767
def calculateBestIntervals(self):
        """"""
        self.__intervals = []
        self.__readAPI(self.__getURL())
        today = datetime.datetime.now().date()

        self.__validInterval(datetime.date(2008, 1, 1), today)
        self.__logger.info("Total number of intervals: " +
                           str(len(self.__intervals)))
        self.__lastDay = today.strftime("%Y-%m-%d")
1305551
def get_last_month_range():
    
    today = date.today()
    # Get the last day for the previous month.
    end_of_last_month = snap_to_beginning_of_month(today) - timedelta(days=1)
    start_of_last_month = snap_to_beginning_of_month(end_of_last_month)
    return (start_of_last_month, end_of_last_month)
874447
def _get_date_range_query(self, start_date, end_date, timespan= 'DAY', date_field= None):
        '''
        
        '''
        if date_field is None:
            date_field = self._date_field
        query ={'q':'*:*',
                'rows':0,
                'facet':'true',
                'facet.range': date_field,
                'facet.range.gap': '+1{}'.format(timespan),
                'facet.range.end': '{}'.format(end_date),
                'facet.range.start': '{}'.format(start_date),
                'facet.range.include': 'all'
                }
        if self._per_shard:
            query['distrib'] = 'false'
        return query
632152
def aggregate(self, start, end):
        '''
        
        '''
        last = self.objects(
            level='daily', date__lte=self.iso(end),
            date__gte=self.iso(start)).order_by('-date').first()
        return last.values[self.name]