Given an expensive query that aggregates temporal data,
    Revise the results to censor before a particular date
342910
def revise_sql(query, id_column, output_table, max_date_column,
               min_date_column, date_column, date, source_id_column=None):
    
    if source_id_column is None:
        source_id_column = id_column

    if hasattr(id_column, '__iter__'):
        id_column = str.join(', ', id_column)
    if hasattr(source_id_column, '__iter__'):
        source_id_column = str.join(', ', source_id_column)

    sql_vars = dict(query=query, id_column=id_column, output_table=output_table,
                    max_date_column=max_date_column, min_date_column=min_date_column,
                    date_column=date_column, date=date, source_id_column=source_id_column)

    sql_vars['ids_query'] = """
    SELECT {id_column} FROM {output_table}
    WHERE {max_date_column} >= '{date}' AND {min_date_column} < '{date}'""" .format(**sql_vars)

    sql_vars['revised_query'] = query.replace(
            '1=1',
            "(({source_id_column}) in (select * from ids_query) and {date_column} < '{date}')"
            .format(**sql_vars))

    new_query = """
    with ids_query as ({ids_query})
    select * from ({revised_query}) t
    """.format(**sql_vars)

    return new_query
986917
@SuppressWarnings("unchecked")
    @Override
    public <R> R query(TemporalQuery<R> query) {
        if (query == TemporalQueries.chronology()) {
            return (R) getChronology();
        } else if (query == TemporalQueries.precision()) {
            return (R) NANOS;
        } else if (query == TemporalQueries.localDate()) {
            return (R) LocalDate.ofEpochDay(toLocalDate().toEpochDay());
        } else if (query == TemporalQueries.localTime()) {
            return (R) toLocalTime();
        } else if (query == TemporalQueries.zone() || query == TemporalQueries.zoneId() || query == TemporalQueries.offset()) {
            return null;
        }
        return super.query(query);
    }
1357121
function processStagingResp(resp, now, evergreen) {
  var keysToData = {};
  for (var key in resp) {
    [].forEach.call(resp[key], function(datedRow) {
      var start =  datedRow['start_date'] ? new Date(datedRow['start_date']) : null;
      var end = datedRow['end_date'] ? new Date(datedRow['end_date']) : null;
      if (evergreen) {
        var isEnabled = datetoggle.isEnabledNow(start, null, now);
      } else {
        var isEnabled = datetoggle.isEnabledNow(start, end, now);
      }
      if (isEnabled) {
        keysToData[key] = datedRow;
      }
    });
  }
  return keysToData;
}
647297
def clean_data(self):
        """"""

        # TODO: Do the same for duration/timedelta
        if "timestamp" in self:
            self._check_timestamp()
            if type(self["timestamp"]) == list:
                def datetime_to_string(dt):
                    return fmt_datetime(dt) if type(dt) == datetime else dt
                self["timestamp"] = list(map(datetime_to_string, self["timestamp"]))
            elif type(self["timestamp"]) == datetime:
                self["timestamp"] = fmt_datetime(self["timestamp"])

        # FIXME: Support list of volumes
        if "volume" in self:
            self["volume"]["unit"] = self["volume"]["unit"].replace("l", "L")

        # FIXME: Support list of weights
        if "weight" in self:
            # Zenobase uses "ug" for micrograms
            if self["weight"]["unit"] in ["mcg", "µg"]:
                self["weight"]["unit"] = "ug"
244517
def prepare_query(self, symbol,  start_date, end_date):
        """"""
        query = \
            'select * from yahoo.finance.historicaldata where symbol = "%s" and startDate = "%s" and endDate = "%s"' \
            % (symbol, start_date, end_date)

        return query
1272497
function _timestampBeforeNow(timestamp) {
      if(!(typeof timestamp === 'string' && dateRegEx.test(timestamp))) {
        throw new TypeError('`revoked` timestamp must be a string.');
      }
      const now = new Date();
      const tsDate = new Date(timestamp);
      return tsDate < now;
    }
266507
private void pruneExcessiveHistoricalRecordsLocked() {
        List<HistoricalRecord> choiceRecords = mHistoricalRecords;
        final int pruneCount = choiceRecords.size() - mHistoryMaxSize;
        if (pruneCount <= 0) {
            return;
        }
        mHistoricalRecordsChanged = true;
        for (int i = 0; i < pruneCount; i++) {
            HistoricalRecord prunedRecord = choiceRecords.remove(0);
            if (DEBUG) {
                Log.i(LOG_TAG, "Pruned: " + prunedRecord);
            }
        }
    }
1281657
def DeleteOldRuns(self, cutoff_timestamp=None):
    """"""
    if cutoff_timestamp is None:
      raise ValueError("cutoff_timestamp can't be None")

    return data_store.REL_DB.DeleteOldCronJobRuns(
        cutoff_timestamp=cutoff_timestamp)
89981
private void resetLastResult() {

        m_result = null;
        m_lastException = null;
        m_categoriesFound = null;
        m_parameterRestriction = null;
        if (!m_parsedQuerySet) {
            // don't reset parsed query if it was deliberately set, otherwise initializing search bean from JSP might fail
            m_parameters.setParsedQuery(null);
        }
    }
939873
def query(cls, resources, time_range, query, resource_type, sampler):
        """"""
        if not isinstance(resources, (list, tuple)):
            resources = [resources]

        now = time.time()
        start_utc = datetime.utcfromtimestamp(now - time_range)
        end_utc = datetime.utcfromtimestamp(now)
        date_format = '%Y-%m-%d %H:%M:%S'
        start = start_utc.strftime(date_format)
        end = end_utc.strftime(date_format)
        query = {'start': start,
                 'end': end,
                 'query': query,
                 'resource_id': resources,
                 'resource_type': resource_type,
                 'sampler': sampler}
        return cls.call('hosting.metric.query', query)
1146540
public static DateTime getUniversalTimestamp(final GroupByQuery query)
  {
    final Granularity gran = query.getGranularity();
    final String timestampStringFromContext = query.getContextValue(CTX_KEY_FUDGE_TIMESTAMP, "");

    if (!timestampStringFromContext.isEmpty()) {
      return DateTimes.utc(Long.parseLong(timestampStringFromContext));
    } else if (Granularities.ALL.equals(gran)) {
      final DateTime timeStart = query.getIntervals().get(0).getStart();
      return gran.getIterable(new Interval(timeStart, timeStart.plus(1))).iterator().next().getStart();
    } else {
      return null;
    }
  }
746432
def purge_old_event_logs(delete_before_days=7):
    
    delete_before_date = timezone.now() - timedelta(days=delete_before_days)
    logs_deleted = EventLog.objects.filter(
        created_on__lte=delete_before_date).delete()
    return logs_deleted
593560
def normalize_date_aggressively(date):
    """"""
    def _strip_last_part(date):
        parts = date.split('-')
        return '-'.join(parts[:-1])

    fake_dates = {'0000', '9999'}
    if date in fake_dates:
        return None
    try:
        return normalize_date(date)
    except ValueError:
        if '-' not in date:
            raise
        else:
            new_date = _strip_last_part(date)
            return normalize_date_aggressively(new_date)
64782
def _BuildQuery(self,
                  subject,
                  attribute=None,
                  timestamp=None,
                  limit=None,
                  is_prefix=False):
    """"""
    args = []
    subject = utils.SmartUnicode(subject)
    criteria = "WHERE aff4.subject_hash=unhex(md5(%s))"
    args.append(subject)
    sorting = ""
    tables = "FROM aff4"

    # Set fields, tables, and criteria and append args
    if attribute is not None:
      if is_prefix:
        tables += " JOIN attributes ON aff4.attribute_hash=attributes.hash"
        prefix = attribute + "%"
        criteria += " AND attributes.attribute like %s"
        args.append(prefix)
      else:
        criteria += " AND aff4.attribute_hash=unhex(md5(%s))"
        args.append(attribute)

    # Limit to time range if specified
    if isinstance(timestamp, (tuple, list)):
      criteria += " AND aff4.timestamp >= %s AND aff4.timestamp <= %s"
      args.append(int(timestamp[0]))
      args.append(int(timestamp[1]))

    fields = "aff4.value, aff4.timestamp"
    if is_prefix:
      fields += ", attributes.attribute"

    # Modify fields and sorting for timestamps.
    if timestamp is None or timestamp == self.NEWEST_TIMESTAMP:
      tables += (" JOIN (SELECT attribute_hash, MAX(timestamp) timestamp "
                 "%s %s GROUP BY attribute_hash) maxtime ON "
                 "aff4.attribute_hash=maxtime.attribute_hash AND "
                 "aff4.timestamp=maxtime.timestamp") % (tables, criteria)
      criteria = "WHERE aff4.subject_hash=unhex(md5(%s))"
      args.append(subject)
    else:
      # Always order results.
      sorting = "ORDER BY aff4.timestamp DESC"
    # Add limit if set.
    if limit:
      sorting += " LIMIT %s" % int(limit)

    query = " ".join(["SELECT", fields, tables, criteria, sorting])

    return (query, args)
769999
function filterBefore(posts) {
      before = moment(before.replace(/\//g, '-'), 'MM-DD-YYYY', true);
      if (!before.isValid()) {
        console.log(chalk.red('Before date is not valid (expecting `MM-DD-YYYY`), ignoring argument.'));
        return posts;
      }

      return posts.filter(function filterPosts(post) {
        return moment(post.date).isBefore(before);
      });
    }
23659
def prune_before(self, timestamp):
        
        n = 0
        pruned = []
        for r in self.resources:
            if (r.timestamp is None):
                raise Exception("Entry %s has no timestamp" % (r.uri))
            elif (r.timestamp >= timestamp):
                pruned.append(r)
            else:
                n += 1
        self.resources = pruned
        return(n)
273872
def DeleteOldCronJobRuns(self, cutoff_timestamp, cursor=None):
    """"""
    query = "DELETE FROM cron_job_runs WHERE write_time < FROM_UNIXTIME(%s)"
    cursor.execute(query,
                   [mysql_utils.RDFDatetimeToTimestamp(cutoff_timestamp)])