Called before a GraphQL query is made in order to stay within Instagram's rate limits.

        :param query_hash: The query_hash parameter of the query.
        :param untracked_queries: True, if 429 has been returned to apply 429 logic.
182261
def _ratecontrol_graphql_query(self, query_hash: str, untracked_queries: bool = False):
        
        if not untracked_queries:
            waittime = self._graphql_query_waittime(query_hash, time.monotonic(), untracked_queries)
            assert waittime >= 0
            if waittime > 10:
                self.log('\nToo many queries in the last time. Need to wait {} seconds, until {:%H:%M}.'
                         .format(waittime, datetime.now() + timedelta(seconds=waittime)))
            time.sleep(waittime)
            if query_hash not in self._graphql_query_timestamps:
                self._graphql_query_timestamps[query_hash] = [time.monotonic()]
            else:
                self._graphql_query_timestamps[query_hash].append(time.monotonic())
        else:
            text_for_429 = ("HTTP error code 429 was returned because too many queries occured in the last time. "
                            "Please do not use Instagram in your browser or run multiple instances of Instaloader "
                            "in parallel.")
            print(textwrap.fill(text_for_429), file=sys.stderr)
            current_time = time.monotonic()
            waittime = self._graphql_query_waittime(query_hash, current_time, untracked_queries)
            assert waittime >= 0
            if waittime > 10:
                self.log('The request will be retried in {} seconds, at {:%H:%M}.'
                         .format(waittime, datetime.now() + timedelta(seconds=waittime)))
            self._dump_query_timestamps(current_time)
            time.sleep(waittime)
738529
def _query(self, query_type, query_str, verbose=False):
        
        # First check query cache
        cached = self.query_cache.get(query_str)
        if cached:
            if verbose:
                print('Returning Cached VT Query Results')
            return cached

        # Not in cache so make the actual query
        if query_type == 'file':
            response = requests.get('https://www.virustotal.com/vtapi/v2/file/report',
                                    params={'apikey': self.apikey, 'resource': query_str, 'allinfo': 1})
        else:
            response = requests.post('https://www.virustotal.com/vtapi/v2/url/report',
                                     params={'apikey': self.apikey, 'resource': query_str, 'allinfo': 1})

        # Make sure we got a json blob back
        try:
            vt_output = response.json()
        except ValueError:
            error_msg = 'VirusTotal no valid response, throttling and trying again...'
            if self.throttle:
                if verbose:
                    print(error_msg)
                time.sleep(30)
                return self._query(query_type, query_str)

            return {'vt_error': error_msg}

        # Check for not-found
        if not vt_output or vt_output['response_code'] == 0:
            output = {'query': query_str, 'not_found': True}
            self.query_cache.set(query_str, output)
            return output

        # Exclude some fields (if summary=True)
        output = {field: vt_output[field] for field in vt_output.keys() if field not in self.exclude}

        # Put the file sha in the output
        output['query'] = query_str

        # Organize the scans fields
        scan_results = collections.Counter()
        for scan in vt_output['scans'].values():
            if 'result' in scan:
                if scan['result']:
                    scan_results[scan['result']] += 1
        output['scan_results'] = scan_results.most_common(5)

        # Pull results in Cache
        self.query_cache.set(query_str, output)

        # Return results
        return output
980215
function requestNextHashTree(ws) {
	db.query("SELECT COUNT(1) AS count_left FROM catchup_chain_balls", function (rows) {
		if (rows.length > 0) {
			if (catchup_balls_at_start == -1) { // first time to get all catchup ball number
				catchup_balls_at_start = rows[0].count_left;
			}
			catchup_balls_left = rows[0].count_left;
		}
	});
	db.query("SELECT ball FROM catchup_chain_balls ORDER BY member_index LIMIT 2", function (rows) {
		if (rows.length === 0)
			return comeOnline();
		if (rows.length === 1) {
			db.query("DELETE FROM catchup_chain_balls WHERE ball=?", [rows[0].ball], function () {
				comeOnline();
			});
			return;
		}

		let from_ball = rows[0].ball;
		let to_ball = rows[1].ball;

		// don't send duplicate requests
		for (let tag in ws.assocPendingRequests) {
			if (ws.assocPendingRequests[tag].request.command === 'get_hash_tree') {
				console.log("already requested hash tree from this peer");
				return;
			}
		}

		//	...
		sendRequest(ws, 'get_hash_tree', {from_ball: from_ball, to_ball: to_ball}, true, handleHashTree);
	});
}
347037
public boolean performBooleanQuery(String queryString, SPARQLQueryBindingSet bindings, Transaction tx, boolean includeInferred, String baseURI) {
        SPARQLQueryDefinition qdef = sparqlManager.newQueryDefinition(queryString);
        if(notNull(baseURI) && !baseURI.isEmpty()){ qdef.setBaseUri(baseURI);}
        qdef.setIncludeDefaultRulesets(includeInferred);
        if (notNull(ruleset)) {qdef.setRulesets(ruleset);}
        if (notNull(getConstrainingQueryDefinition())){
        	qdef.setConstrainingQueryDefinition(getConstrainingQueryDefinition());
            qdef.setDirectory(getConstrainingQueryDefinition().getDirectory());
            qdef.setCollections(getConstrainingQueryDefinition().getCollections());
            qdef.setResponseTransform(getConstrainingQueryDefinition().getResponseTransform());
            qdef.setOptionsName(getConstrainingQueryDefinition().getOptionsName());
        	}
        if(notNull(graphPerms)){ qdef.setUpdatePermissions(graphPerms);}
        return sparqlManager.executeAsk(qdef,tx);
    }
44916
def _dump_query_timestamps(self, current_time: float):
        """"""
        windows = [10, 11, 15, 20, 30, 60]
        print("GraphQL requests:", file=sys.stderr)
        for query_hash, times in self._graphql_query_timestamps.items():
            print("  {}".format(query_hash), file=sys.stderr)
            for window in windows:
                reqs_in_sliding_window = sum(t > current_time - window * 60 for t in times)
                print("    last {} minutes: {} requests".format(window, reqs_in_sliding_window), file=sys.stderr)
873228
def query_bypass(self, query, raw_output=True):
        ''' 
        '''
        if not isinstance(query, dict):
            raise BadQueryException('Query must be dict.')

        self.__query = query
        if raw_output:
            self._raw_output = True
            return self.__get_query_result().cursor
        else:
            return self
266107
def query=(new_query)
      if new_query && !new_query.respond_to?(:to_str)
        raise TypeError, "Can't convert #{new_query.class} into String."
      end
      @query = new_query ? new_query.to_str : nil

      # Reset dependent values
      remove_instance_variable(:@normalized_query) if defined?(@normalized_query)
      remove_composite_values
    end
1214760
def graphql_requests(self, *queries):
        
        data = {
            "method": "GET",
            "response_format": "json",
            "queries": graphql_queries_to_json(*queries),
        }
        return tuple(
            self._post(self.req_url.GRAPHQL, data, fix_request=True, as_graphql=True)
        )
743771
function _queryForTargetSessions(url, minDbSeq) {
    var where = { isConnected: true };
    if (minDbSeq) {
      where.connectedAtDbSeq = { gt: minDbSeq };
    }
    return Session.findAll({
        where: where,
        attributes: [
            'sessionId',
            'connectedAtDbSeq',
        ],
        include: [{
            model: Route,
            where: { routeUrl: url, weight: { gt: 0 } },
            attributes: []
        }],
        group: '`Session`.`sessionId`',
    }, { raw: true })
    .then(function(sessions) {
      var sessionIds = [];
      var dbSeq = -1;
      for (var i = 0; i < sessions.length; i++) {
        var session = sessions[i];
        var sessionId = session['sessionId'];
        sessionIds.push(sessionId);
        dbSeq = Math.max(session['connectedAtDbSeq'], dbSeq);
      }
      return { sessionIds: sessionIds, dbSeq: dbSeq };
    })
  }
330165
def parse_uri_query_params(query)
      query.to_s.split('&'.freeze).reduce({}) do |h, p|
        k, v = p.split('='.freeze, 2)
        v = URI::Generic::DEFAULT_PARSER.unescape(v) if v
        h[k.to_sym] = v || true
        h
      end
    end
357353
def call(hash)
      logger.debug { "continuation req_id #{req_id}, got hash: #{hash.inspect}" }
      @rval = hash.values_at(*METH_TO_ASYNC_RESULT_KEYS.fetch(meth))
      logger.debug { "delivering result #{@rval.inspect}" }
      deliver!
    end
685918
def execute_cql_query(self, query, compression):
    
    self._seqid += 1
    d = self._reqs[self._seqid] = defer.Deferred()
    self.send_execute_cql_query(query, compression)
    return d
364923
def check_query(query):
    
    q = query.lower()
    if "select " not in q:
        raise InvalidQuery("SELECT word not found in the query: {0}".format(query))
    if " from " not in q:
        raise InvalidQuery("FROM word not found in the query: {0}".format(query))
1123319
def query(self, query=None):
        
        if query is None:
            return self.url.query
        self.url.query = query
1086624
def _query_wrap(fun, *args, **kwargs):
    
    with _query_lock:
        global _last_query_time
        since_last_query = time.time() - _last_query_time
        if since_last_query < QUERY_WAIT_TIME:
            time.sleep(QUERY_WAIT_TIME - since_last_query)
        _last_query_time = time.time()
        return fun(*args, **kwargs)
1076806
def setQuery(self, query):
        
        if not self.isVisible():
            self._loadQuery = query
        else:
            self._loadQuery = None
            
            if self._initialized and hash(query) == hash(self.query()):
                return
            
            self._initialized = True
            self.clear()
            self.addContainer(query)
159098
public function removeQueryHash($hash)
    {
        $queryHashes =& $this->getArchive()->getByRef('query_hashes', array());
        unset($queryHashes[array_search($hash, $queryHashes)]);
        $queryHashes = array_values($queryHashes);
    }