Add cached values for the specified date range and query
508839
def add_cache(self, namespace, key, query_hash, length, cache):
        """"""
        start = 0
        bulk_insert = self.bulk_insert
        cache_len = len(cache)
        row = '(%s,%s,%s,%s,%s,%s)'
        query = 'INSERT INTO gauged_cache ' \
            '(namespace, key, "hash", length, start, value) VALUES '
        execute = self.cursor.execute
        query_hash = self.psycopg2.Binary(query_hash)
        while start < cache_len:
            rows = cache[start:start+bulk_insert]
            params = []
            for timestamp, value in rows:
                params.extend((namespace, key, query_hash, length,
                               timestamp, value))
            insert = (row + ',') * (len(rows) - 1) + row
            execute(query + insert, params)
            start += bulk_insert
        self.db.commit()
7848
private void addQueryParams(final Request request) {
        if (absoluteDateCreated != null) {
            request.addQueryParam("DateCreated", absoluteDateCreated.toString(Request.QUERY_STRING_DATE_TIME_FORMAT));
        } else if (rangeDateCreated != null) {
            request.addQueryDateTimeRange("DateCreated", rangeDateCreated);
        }

        if (getPageSize() != null) {
            request.addQueryParam("PageSize", Integer.toString(getPageSize()));
        }
    }
344939
def _fill_cache(self):
        """"""
        for irow in range(len(self._table)):
            job_details = self.make_job_details(irow)
            self._cache[job_details.fullkey] = job_details
685153
def date_range_filter(range_name):
    """"""

    filter_days = list(filter(
        lambda time: time["label"] == range_name,
        settings.CUSTOM_SEARCH_TIME_PERIODS))
    num_days = filter_days[0]["days"] if len(filter_days) else None

    if num_days:
        dt = timedelta(num_days)
        start_time = timezone.now() - dt
        return Range(published={"gte": start_time})
    return MatchAll()
1163058
def dateadd(value: fields.DateTime(),
            addend: fields.Int(validate=Range(min=1)),
            unit: fields.Str(validate=OneOf(['minutes', 'days']))='days'):
    """"""
    value = value or dt.datetime.utcnow()
    if unit == 'minutes':
        delta = dt.timedelta(minutes=addend)
    else:
        delta = dt.timedelta(days=addend)
    result = value + delta
    return {'result': result}
300314
public Query addDateParameter(java.util.Date date) {
        return addParameter(new Date(date.getTime()));
    }
176346
def _set_cached_value(self, xblock, value):
        """"""
        # pylint: disable=protected-access
        if not hasattr(xblock, '_field_data_cache'):
            xblock._field_data_cache = {}
        xblock._field_data_cache[self.name] = value
132783
public function performQuery(string $viewId, DateTime $startDate, DateTime $endDate, string $metrics, array $others = [])
    {
        $cacheName = $this->determineCacheName(func_get_args());

        if ($this->cacheLifeTimeInMinutes == 0) {
            $this->cache->forget($cacheName);
        }

        return $this->cache->remember($cacheName, $this->cacheLifeTimeInMinutes, function () use ($viewId, $startDate, $endDate, $metrics, $others) {
            $result = $this->service->data_ga->get(
                "ga:{$viewId}",
                $startDate->format('Y-m-d'),
                $endDate->format('Y-m-d'),
                $metrics,
                $others
            );

            while ($nextLink = $result->getNextLink()) {
                if (isset($others['max-results']) && count($result->rows) >= $others['max-results']) {
                    break;
                }

                $options = [];

                parse_str(substr($nextLink, strpos($nextLink, '?') + 1), $options);

                $response = $this->service->data_ga->call('get', [$options], 'Google_Service_Analytics_GaData');

                if ($response->rows) {
                    $result->rows = array_merge($result->rows, $response->rows);
                }

                $result->nextLink = $response->nextLink;
            }

            return $result;
        });
    }
130861
function cacheQueryResult (cached) {
    // list of ids that where not cached
    this.uncachedIds = []
    // check result set for uncached ids
    for (var i=0; i < this.numIds; i++) {
        var cachedValue = undefined
        // decode result if not null
        if (cached[i] !== null) {
            try {
                // decode JSON
                cachedValue = JSON.parse(cached[i])
                // add cached view flag
                cachedValue._cachedView = true
            }
            catch (err) {
                // ignore errors
            }
        }
        // if there is cached value use otherwise add id to fetch list
        defined(cachedValue)
            ? this.cached.push(cachedValue)
            : this.uncachedIds.push(this.ids[i])
    }
    // debug
    debug('view:id:record:uncachedIds', this.uncachedIds)
    // if all records were cached the return result from cache
    if (this.uncachedIds.length === 0) {
        // set cached view flag
        this.cached._cachedView = true
        // return cached results
        return this.cached
    }
    // load uncached records and return all
    else {
        return this.loadUncached()
    }
}
632394
def set_added_since(self, added):
        
        self._query_params += str(QueryParam.DAYS_OLD) + str(added)
501618
function _buildQuery(){

            var url         = data.url;
            var cache       = typeof data.cache !== 'undefined' ? !!data.cache : true;
            var queryString = data.queryString || '';
            var _data       = data.data;

            //add a cache buster
            if(cache === false){
                queryString += '&ajabuster=' + new Date().getTime();
            }

            url = appendQueryString(url, queryString);

            if(_data && !_dataInBody()){
                url =  appendQueryString(url, _data);
            }
            return url;
        }
731760
def __store_query(self, query_items):
        
        temp_index = self._current_query_index
        if len(self._queries) - 1 < temp_index:
            self._queries.append([])

        self._queries[temp_index].append(query_items)
1126115
protected void applyCacheHints(TypedQuery<?> typedQuery, SearchParameters sp) {
        if (sp.isCacheable()) {
            typedQuery.setHint("org.hibernate.cacheable", true);

            if (sp.hasCacheRegion()) {
                typedQuery.setHint("org.hibernate.cacheRegion", sp.getCacheRegion());
            } else {
                typedQuery.setHint("org.hibernate.cacheRegion", cacheRegion);
            }
        }
    }
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)
290265
private RequestTemplate appendQuery(String name,
                                      Iterable<String> values,
                                      CollectionFormat collectionFormat) {
    if (!values.iterator().hasNext()) {
      /* empty value, clear the existing values */
      this.queries.remove(name);
      return this;
    }

    /* create a new query template out of the information here */
    this.queries.compute(name, (key, queryTemplate) -> {
      if (queryTemplate == null) {
        return QueryTemplate.create(name, values, this.charset, collectionFormat);
      } else {
        return QueryTemplate.append(queryTemplate, values, collectionFormat);
      }
    });
    return this;
  }
917297
function(text, options) {
    var execute, queried;
    queried = p.defer();
    // caching disabled unless duration is specified
    options = options != null ? options : {
      duration: 0
    };
    execute = function(params) {
      return db.prepare(text).then(function(stmt) {
        return stmt.execute(params).then(function(results) {
          if (options.duration > 0) {
            cache.store(text, results.rows, options.duration);
          }
          return queried.resolve(results.rows);
        }).done();
      }).done();
    };
    // return results directly if cache hit, run query if cache miss
    cache.get(text).then(function(results) {
      return queried.resolve(results);
    }, function(err) {
      if (err != null) {
        return queried.reject(err);
      } else {
        return execute();
      }
    }).done();
    return queried.promise;
  }
509309
function store($table, $where, $fields, $append=false)
	{
		if(!$append)
			$n = $this->get("SELECT COUNT(*) FROM `".addslashes($table)."` WHERE $where");

		if(!$append && $n>0)
			$res = $this->query("UPDATE `".addslashes($table)."` ".$this->make_string_set($fields)." WHERE $where");
		else
			$res = $this->query("REPLACE INTO `".addslashes($table)."` ".$this->make_string_values($fields));

		if($res === false)
			throw new Exception("Invalid query: " . mysql_error($this->dbh) ." ");
	}