query(user string) -- make http request to duckduckgo api, to get result
	in json format, then call parse_result.
769334
def query(string):
	
	url = "https://api.duckduckgo.com/?q="
	formating = "&format=json"
	query_string = url+'+'.join(string)+formating
	try:
		result = json.loads(requests.get(query_string).text)
	except:
		print "I'm sorry! Something went wrong. Maybe we could try again later."
		return
	parse_result(result)
430058
def parse_request(request, input_schema, raw):
    """"""

    request.json = {}
    if not raw:
        body = yield from request.read()
        if body:
            try:
                request.json = json.loads(body.decode('utf-8'))
            except ValueError as e:
                request.json = {"malformed_json": body.decode('utf-8')}
                raise aiohttp.web.HTTPBadRequest(text="Invalid JSON {}".format(e))

    # Parse the query string
    if len(request.query_string) > 0:
        for (k, v) in urllib.parse.parse_qs(request.query_string).items():
            request.json[k] = v[0]

    if input_schema:
        try:
            jsonschema.validate(request.json, input_schema)
        except jsonschema.ValidationError as e:
            log.error("Invalid input query. JSON schema error: {}".format(e.message))
            raise aiohttp.web.HTTPBadRequest(text="Invalid JSON: {} in schema: {}".format(
                e.message,
                json.dumps(e.schema)))

    return request
1319530
def parse_query(qs, d = '&;')
      params = {}
      (qs || '').split(/[#{d}] */n).each do |p|
        k, v = p.split('=', 2).map { |str| str } # NOTE: uri_unescape
        k = k.to_sym
        if cur = params[k]
          if cur.class == Array
            params[k] << v
          else
            params[k] = [cur, v]
          end
        else
          params[k] = v
        end
      end
      params
    end
246035
def parse_querystring(self, req: Request, name: str, field: Field) -> typing.Any:
        """"""
        return core.get_value(req.query, name, field)
660862
def POST_query(self, req_hook, req_args):
        '''  '''
        # HTTP POST queries require keyManagerTokens and sessionTokens
        headers = {'Content-Type': 'application/json',
                   'sessionToken': self.__session__,
                   'keyManagerToken': self.__keymngr__}

        # HTTP POST query to keymanager authenticate API
        try:
            if req_args is None:
                response = requests.post(self.__url__ + req_hook,
                                         headers=headers,
                                         verify=True)
            else:
                response = requests.post(self.__url__ + req_hook,
                                         headers=headers,
                                         data=req_args,
                                         verify=True)
        except requests.exceptions.RequestException as err:
            self.logger.error(err)
            return '500', 'Internal Error in RESTful.POST_query()'
        # return the token
        return response.status_code, response.text
329000
def _osquery(sql, format='json'):
    '''
    
    '''
    ret = {
        'result': True,
    }

    cmd = ['osqueryi'] + ['--json'] + [sql]
    res = __salt__['cmd.run_all'](cmd)
    if res['stderr']:
        ret['result'] = False
        ret['error'] = res['stderr']
    else:
        ret['data'] = salt.utils.json.loads(res['stdout'])
    log.debug('== %s ==', ret)
    return ret
12429
def _query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
    '''
    
    '''
    api_key = config.get_cloud_config_value(
        'api_key',
        get_configured_provider(),
        __opts__,
        search_global=False,
    )
    management_host = config.get_cloud_config_value(
        'management_host',
        get_configured_provider(),
        __opts__,
        search_global=False,
        default='api.vultr.com'
    )
    url = 'https://{management_host}/v1/{path}?api_key={api_key}'.format(
        management_host=management_host,
        path=path,
        api_key=api_key,
    )

    if header_dict is None:
        header_dict = {}

    result = __utils__['http.query'](
        url,
        method=method,
        params=params,
        data=data,
        header_dict=header_dict,
        port=443,
        text=True,
        decode=decode,
        decode_type='json',
        hide_fields=['api_key'],
        opts=__opts__,
    )
    if 'dict' in result:
        return result['dict']

    return result
1042034
def create_request(query):
    
    yarr_url = app.config.get('YARR_URL', False)

    if not yarr_url:
        raise('No URL to Yarr! server specified in config.')

    api_token = app.config.get('YARR_API_TOKEN', False)
    headers = {'X-API-KEY': api_token} if api_token else {}
    payload = {'q': query}
    url = '%s/search' % yarr_url

    return requests.get(url, params=payload, headers=headers)
1244909
def query(query_str)
      # puts "conent #{content}"
      res = conn.post '/query/', {query: query_str, time: Time.now.to_i}.to_json do |req|
        req.headers['Content-Type'] = 'application/json'
        req.headers['X-Requested-With'] = 'XMLHttpRequest'
        req['Cookie'] = "csrftoken=#{csrf_token}"
        req.headers['X-CSRFToken'] = csrf_token
      end
      JSON.parse(res.body)
   end
1122357
def query(self):
        
        query_context = QueryContext(**json.loads(request.form.get('query_context')))
        security_manager.assert_datasource_permission(query_context.datasource)
        payload_json = query_context.get_payload()
        return json.dumps(
            payload_json,
            default=utils.json_int_dttm_ser,
            ignore_nan=True,
        )
21896
function fetch_query() {
            const key = arg.query_id;
            let value = store_struct.query_result_map.get(key);
            if (endpoint_payload) {
                value = {
                    query: String(arg.query_string),
                    result: JSON.parse(JSON.stringify(endpoint_payload)),
                    }; // eslint-disable-line indent
                store_struct.query_result_map.set(key, value);
            }
            return value
                && (String(arg.query_string) === value.query || undefined)
                && value.result
                ; // eslint-disable-line indent
        }
869623
def __yahoo_request(query):
    
    query = quote(query)
    url = 'https://query.yahooapis.com/v1/public/yql?q=' + query + \
        '&format=json&env=store://datatables.org/alltableswithkeys'

    response = urlopen(url).read()

    return json.loads(response.decode('utf-8'))['query']['results']
678094
function query (query, params, options, session) {
    // require string for query
    if (typeof query !== 'string') {
        throw new Error('query error: query must be string')
    }
    // validate optional args - create objects if not passed in
    options = requireValidOptionalObject(options)
    params = requireValidOptionalObject(params)
    session = requireValidOptionalObject(session)
    // if the no insert flag is set then do not run insert queries
    if (session.noInsert && query.match(/^\s*INSERT/i)) {
        return Promise.resolve()
    }
    // get unique if for query
    var dbQueryId = randomUniqueId()
    // log query start
    this.logQuery(query, params, options, session, dbQueryId)
    // perform query using promisified interface
    return this.client.queryPromise(query, params, options)
    // success
    .then(res => {
        // perform formatting on response data
        formatResponse(res)
        // log response
        this.logQueryResponse(dbQueryId, options, res)
        // resolve with response data
        return res
    })
    // error
    .catch(err => {
        // log error
        this.logQueryError(dbQueryId, options, err)
        // reject with error
        return Promise.reject(err)
    })
}
279932
def parse_result(result):
	

	if(result['Type'] == 'D'):
		print """There is more than one answer for this. Try making your query\
		more specific. For example, if you want to learn about apple the company\
		and not apple the fruit, try something like apple inc or apple computers.  
		"""
	
	elif(result['Type'] == 'A'):
		print result['AbstractText']
		print '\nResults from DuckDuckGo'
	
	elif(result['Type'] == 'C'):
		for entry in result['RelatedTopics']:
			print entry['Text']
			print "\n"
	else:
		print "I do not know how to process this query at the moment."
185175
def GET_query(self, req_hook, req_args):
        '''  '''
        # GET request methods only require sessionTokens
        headers = {'content-type': 'application/json',
                   'sessionToken': self.__session__}

        # HTTP GET query method using requests module
        try:
            if req_args is None:
                response = requests.get(self.__url__ + req_hook,
                                        headers=headers,
                                        verify=True)
            else:
                response = requests.get(self.__url__ + req_hook + str(req_args),
                                        headers=headers,
                                        verify=True)
        except requests.exceptions.RequestException as err:
            self.logger.error(err)
            return '500', 'Internal Error in RESTful.GET_query()'
        # return the token
        return response.status_code, response.text
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
238385
function query(base, q, callback) {
    // Added unescape to fix URI errors resulting from hexadecimal escape sequences
    var url = util.format("%s?%s", base, querystring.unescape(querystring.stringify(q)));
    request(url, function (err, response) {
        if (err) return callback(err);
        callback(null, response.body);
    });
}