Return types if homogenous within sample

    Compare up to 10 rows of results to determine homogeneity.

    DESCRIBE and CONSTRUCT queries, for example,

    :param result_vars:
    :param sparql_results_json:
179915
def _get_types_from_sample(result_vars, sparql_results_json):
    
    total_bindings = len(sparql_results_json['results']['bindings'])
    homogeneous_types = {}
    for result_var in result_vars:
        var_types = set()
        var_datatypes = set()
        for i in range(0, min(total_bindings, 10)):
            binding = sparql_results_json['results']['bindings'][i]
            rdf_term = binding.get(result_var)
            if rdf_term is not None:  # skip missing values
                var_types.add(rdf_term.get('type'))
                var_datatypes.add(rdf_term.get('datatype'))
        if len(var_types) > 1 or len(var_datatypes) > 1:
            return None  # Heterogeneous types
        else:
            homogeneous_types[result_var] = {
                'type': var_types.pop() if var_types else None,
                'datatype': var_datatypes.pop() if var_datatypes else None
            }

    return homogeneous_types
192588
def _simsearch_to_simresult(self, sim_resp: Dict, method: SimAlgorithm) -> SimResult:
        

        sim_ids = get_nodes_from_ids(sim_resp['query_IRIs'])
        sim_resp['results'] = OwlSim2Api._rank_results(sim_resp['results'], method)

        # get id type map:
        ids = [result['j']['id'] for result in sim_resp['results']]
        id_type_map = get_id_type_map(ids)

        matches = []

        for result in sim_resp['results']:
            matches.append(
                SimMatch(
                    id=result['j']['id'],
                    label=result['j']['label'],
                    rank=result['rank'],
                    score=result[OwlSim2Api.method2key[method]],
                    type=id_type_map[result['j']['id']][0],
                    taxon=get_taxon(result['j']['id']),
                    significance="NaN",
                    pairwise_match=OwlSim2Api._make_pairwise_matches(result)
                )
            )

        return SimResult(
            query=SimQuery(
                ids=sim_ids,
                unresolved_ids=sim_resp['unresolved'],
                target_ids=[[]]
            ),
            matches=matches,
            metadata=SimMetadata(
                max_max_ic=self.statistics.max_max_ic
            )
        )
747461
def is_get_query_with_results(results):
        
        return results and EsConst.FOUND in results and results[EsConst.FOUND] and EsConst.FIELDS in results
343710
def __process_results(results):
    
    if 'no match' in results and 'returning 0 elements' in results:
        return []

    result_list = []

    # Splts the result and cuts first and last dataset which are comments
    split = results.split(sep='\n\n')[1:-1]

    for entry in split:
        entry_dict = {}
        for value in entry.split('\n'):
            if len(value) < 1:
                continue
            (desc, val) = value.split(': ')
            entry_dict[desc.replace('-', '')] = val.strip(' ')
        result_list.append(entry_dict)
    return result_list
542126
def _get_series_result_type(result, objs=None):
    
    from pandas import SparseSeries, SparseDataFrame, DataFrame

    # concat Series with axis 1
    if isinstance(result, dict):
        # concat Series with axis 1
        if all(isinstance(c, (SparseSeries, SparseDataFrame))
               for c in result.values()):
            return SparseDataFrame
        else:
            return DataFrame

    # otherwise it is a SingleBlockManager (axis = 0)
    if result._block.is_sparse:
        return SparseSeries
    else:
        return objs[0]._constructor
435395
def objects(self, json_result=False):
        
        self.rows_num = 0
        query = self.query()
        if not isinstance(query, (orm.Result, list, dict)):
            query = do_(query)
        for record in query:
            self.rows_num += 1
            r = self.object(record, json_result)
            self._cal_sum(record)
            yield r
        total = self._render_sum(True)
        if total:
            yield total
97998
def _pull_query_results(resultset):
    '''
    
    '''
    _results = collections.defaultdict(lambda: {})
    for _header, _values in resultset.items():
        _header, _group_tags = _header
        if _group_tags:
            _results[_header][salt.utils.json.dumps(_group_tags)] = [_value for _value in _values]
        else:
            _results[_header] = [_value for _value in _values]
    return dict(sorted(_results.items()))
266891
function cacheResults (results) {
    // get id column name
    var idColumn = this.query.model.columnName('id')
    // arguments for multi-set
    var setArgs = []
    // args are list of key, value, key, value
    _.each(results, result => {
        // JSON encode result
        try {
            var cacheValue = JSON.stringify(result)
        }
        catch (err) {
            // ignore errors
        }
        // cache value
        if (defined(cacheValue)) {
            // get cache key
            var cacheKey = this.cacheKey(result[idColumn])
            // debug
            debug('id:set', cacheKey)
            // add to list to cache
            setArgs.push(cacheKey, cacheValue)
        }
    })
    // cache results
    if (setArgs.length > 0) {
        return this.cache.redis.msetAsync(setArgs)
    }
}
263222
def _get_results_by_type(self, type):
        
        instance = self._create_model_by_type(type)

        key = instance.get_key_name()

        query = instance.new_query()

        query = self._use_with_trashed(query)

        return query.where_in(key, self._gather_keys_by_type(type).all()).get()
306964
function cacheResults (results) {
    // get current max record number
    return this.cache.model.maxRecordNumber({
        session: this.query.session,
    }).then(n => {
        // if state has changed do not cache
        if (n !== this.initialMaxRecordNumber) {
            return
        }
        // JSON encode data to cache
        try {
            var cacheValue = JSON.stringify({
                n: n,
                v: results,
            })
        }
        catch (err) {
            // ignore errors
        }
        // cache result
        if (cacheValue) {
            debug('view:select:collection:set', this.selectCacheKey)
            return this.cache.redis.setAsync(this.selectCacheKey, cacheValue)
        }
    })
}
1049398
def _result_object(result):
    
    content_type = result.headers.get('content-type', None)

    if content_type is None or content_type.startswith('application/json'):
        # This function is only called when there is content expected.
        # Therefore, a response without content will result in a ParseError.
        try:
            return result.json(object_pairs_hook=OrderedDict)
        except ValueError as exc:
            raise ParseError(
                "JSON parse error in HTTP response: {}. "
                "HTTP request: {} {}. "
                "Response status {}. "
                "Response content-type: {!r}. "
                "Content (max.1000, decoded using {}): {}".
                format(exc.args[0],
                       result.request.method, result.request.url,
                       result.status_code, content_type, result.encoding,
                       _text_repr(result.text, 1000)))
    elif content_type.startswith('text/html'):
        # We are in some error situation. The HMC returns HTML content
        # for some 5xx status codes. We try to deal with it somehow,
        # but we are not going as far as real HTML parsing.
        m = re.search(r'charset=([^;,]+)', content_type)
        if m:
            encoding = m.group(1)  # e.g. RFC "ISO-8859-1"
        else:
            encoding = 'utf-8'
        try:
            html_uni = result.content.decode(encoding)
        except LookupError:
            html_uni = result.content.decode()

        # We convert to one line to be regexp-friendly.
        html_oneline = html_uni.replace('\r\n', '\\n').replace('\r', '\\n').\
            replace('\n', '\\n')

        # Check for some well-known errors:
        if re.search(r'javax\.servlet\.ServletException: '
                     r'Web Services are not enabled\.', html_oneline):
            html_title = "Console Configuration Error"
            html_details = "Web Services API is not enabled on the HMC."
            html_reason = HTML_REASON_WEB_SERVICES_DISABLED
        else:
            m = re.search(
                r'<title>([^<]*)</title>.*'
                r'<h2>Details:</h2>(.*)(<hr size="1" noshade>)?</body>',
                html_oneline)
            if m:
                html_title = m.group(1)
                # Spend a reasonable effort to make the HTML readable:
                html_details = m.group(2).replace('<p>', '\\n').\
                    replace('<br>', '\\n').replace('\\n\\n', '\\n').strip()
            else:
                html_title = "Console Internal Error"
                html_details = "Response body: {!r}".format(html_uni)
            html_reason = HTML_REASON_OTHER
        message = "{}: {}".format(html_title, html_details)

        # We create a minimal JSON error object (to the extent we use it
        # when processing it):
        result_obj = {
            'http-status': result.status_code,
            'reason': html_reason,
            'message': message,
            'request-uri': result.request.url,
            'request-method': result.request.method,
        }
        return result_obj
    elif content_type.startswith('application/vnd.ibm-z-zmanager-metrics'):
        content_bytes = result.content
        assert isinstance(content_bytes, six.binary_type)
        return content_bytes.decode('utf-8')  # as a unicode object
    else:
        raise ParseError(
            "Unknown content type in HTTP response: {}. "
            "HTTP request: {} {}. "
            "Response status {}. "
            "Response content-type: {!r}. "
            "Content (max.1000, decoded using {}): {}".
            format(content_type,
                   result.request.method, result.request.url,
                   result.status_code, content_type, result.encoding,
                   _text_repr(result.text, 1000)))
638248
function _get_result(Type) {
	return function(rows) {
		if(!rows) { throw new TypeError("failed to parse result"); }
		var doc = rows.shift();
		if(!doc) { return; }

		if(doc instanceof Type) {
			return doc;
		}

		var obj = {};
		ARRAY(Object.keys(doc)).forEach(function(key) {

			if(key === 'documents') {
				obj['$'+key] = {};
				ARRAY(Object.keys(doc[key])).forEach(function(k) {
					if(is.uuid(k)) {
						obj['$'+key][k] = _get_result(NoPg.Document)([doc[key][k]]);
					} else {
						obj['$'+key][k] = doc[key][k];
					}
				});
				return;
			}

			obj['$'+key] = doc[key];
		});

		_parse_object_expressions(obj);

		return new Type(obj);
	};
}
681537
def parse_result(cls, result):
        
        if len(result) == 3:
            items, count, context = result
        else:
            context = {}
            items, count = result
        return items, count, context
929535
def _to_variable_type(x, records):
    
    var_mapping = {"string": "String", "File": "File", "null": "String",
                   "long": "Float", "double": "Float", "int": "Int"}
    if isinstance(x, dict):
        if x["type"] == "record":
            struct_name, records = _record_to_struct(x, records)
            return struct_name, records
        else:
            assert x["type"] == "array", x
            cur_type, records = _to_variable_type(x["items"], records)
            return "Array[%s]" % cur_type, records
    elif isinstance(x, (list, tuple)):
        vars = [v for v in x if v != "null"]
        return var_mapping[vars[0]], records
    else:
        return var_mapping[x], records
779057
private static Row row(List<StatementResult> results) {
		Row row = results.get( 0 ).getData().get( 0 );
		return row;
	}
1288534
function recordResult (results) {
    // if only ids were selected the return result object to fetch records
    if (this.query.select.isSelectOnlyIds) {
        // build result object
        var result = new ImmutableCoreModelResult({
            query: this.query,
            results: results,
            applyView: true,
        })
        // return result or all records if specified
        return this.query.args.all ? result.all() : result
    }
    // otherwise return ImmutableCoreModelInstance record(s)
    else {
        // if query is for a single record then return record or undefined
        if (this.query.args.limit === 1) {
            // if there are not results return undefined
            if (!results.length) {
                return undefined
            }
            // apply model view to record
            return Promise.resolve(this.applyModelViewRecord(results[0]))
            // resolve with instance
            .then(result => this.newRecordInstance(result))
        }
        // if query is for all records then return all
        else {
            // apply model views to each record
            return Promise.map(results, result => {
                // apply model view to record
                return this.applyModelViewRecord(result)
                // resolve with instance
                .then(result => this.newRecordInstance(result))
            })
        }
    }
}
244103
def search(type, query)
      results = []
      search = request('getResultsFromSearch', type: type, query: query)
      results = search['result'].map do |data|
        next Song.new data if type == 'Songs'
        next Playlist.new(self, data) if type == 'Playlists'
        data
      end if search.key?('result')
      results
    end