Normalizes a JSON search response so that PB and HTTP have the
        same return value
439945
def _normalize_json_search_response(self, json):
        
        result = {}
        if 'facet_counts' in json:
            result['facet_counts'] = json[u'facet_counts']
        if 'grouped' in json:
            result['grouped'] = json[u'grouped']
        if 'stats' in json:
            result['stats'] = json[u'stats']
        if u'response' in json:
            result['num_found'] = json[u'response'][u'numFound']
            result['max_score'] = float(json[u'response'][u'maxScore'])
            docs = []
            for doc in json[u'response'][u'docs']:
                resdoc = {}
                if u'_yz_rk' in doc:
                    # Is this a Riak 2.0 result?
                    resdoc = doc
                else:
                    # Riak Search 1.0 Legacy assumptions about format
                    resdoc[u'id'] = doc[u'id']
                    if u'fields' in doc:
                        for k, v in six.iteritems(doc[u'fields']):
                            resdoc[k] = v
                docs.append(resdoc)
            result['docs'] = docs
        return result
102663
def normalize_cell_value(value):
    
    if isinstance(value, dict) or isinstance(value, list):
        return json.dumps(value)
    return value
1373437
function normalizeUrl(url) {
  if (!IS_ABSOLUTE.test(url)) {
    return (0, _normalizeUrl2['default'])(url).replace('http://', '');
  } else {
    return (0, _normalizeUrl2['default'])(url);
  }
}
856635
def normalize_url(url):
    """"""
    if url.endswith('.json'):
        url = url[:-5]
    if url.endswith('/'):
        url = url[:-1]
    return url
865864
def process_json_response(self, response):
        """"""

        response_json = response.json()

        # handle errors
        code_key = "code"
        if code_key in response_json and response_json[code_key] != constants.HTTP_CODE_OK:
            code = response_json[code_key]

            message = response_json
            if "message" in response_json:
                message = response_json["message"]
            elif "code_description" in response_json:
                message = response_json["code_description"]

            if code == constants.HTTP_FORBIDDEN:
                raise housecanary.exceptions.UnauthorizedException(code, message)
            if code == constants.HTTP_TOO_MANY_REQUESTS:
                raise housecanary.exceptions.RateLimitException(code, message, response)
            else:
                raise housecanary.exceptions.RequestException(code, message)

        request_url = response.request.url

        endpoint_name = self._parse_endpoint_name_from_url(request_url)

        return Response.create(endpoint_name, response_json, response)
934893
def _json_safe(cls, value):
        """"""
        # Date
        if type(value) == date:
            return str(value)

        # Datetime
        elif type(value) == datetime:
            return value.strftime('%Y-%m-%d %H:%M:%S')

        # Object Id
        elif isinstance(value, ObjectId):
            return str(value)

        # Frame
        elif isinstance(value, _BaseFrame):
            return value.to_json_type()

        # Lists
        elif isinstance(value, (list, tuple)):
            return [cls._json_safe(v) for v in value]

        # Dictionaries
        elif isinstance(value, dict):
            return {k:cls._json_safe(v) for k, v in value.items()}

        return value
874972
def _check_scihub_response(response, test_json=True):
    
    # Prevent requests from needing to guess the encoding
    # SciHub appears to be using UTF-8 in all of their responses
    response.encoding = 'utf-8'
    try:
        response.raise_for_status()
        if test_json:
            response.json()
    except (requests.HTTPError, ValueError):
        msg = "Invalid API response."
        try:
            msg = response.headers['cause-message']
        except:
            try:
                msg = response.json()['error']['message']['value']
            except:
                if not response.text.strip().startswith('{'):
                    try:
                        h = html2text.HTML2Text()
                        h.ignore_images = True
                        h.ignore_anchors = True
                        msg = h.handle(response.text).strip()
                    except:
                        pass
        api_error = SentinelAPIError(msg, response)
        # Suppress "During handling of the above exception..." message
        # See PEP 409
        api_error.__cause__ = None
        raise api_error
55302
function processNormalizedResponse(normalized, req, res){
  if(!delay){
    // stash normalized in cache and return normalized
    console.log('\n\nDone!\n\n')
    if(!req.session.media_cache) req.session.media_cache = normalized
    // console.dir(req.session.media_cache)
    return res.json(normalized)
  }
  else{
    setTimeout(function(){
      // We have to check again for delay due to race conditions.
      if(delay) return processNormalizedResponse(normalized, req, res)
    },10)
  }
}
1094443
function normalizeResource(resource) {
    if (!resource) {
      return resource;
    }
    var i = resource.indexOf('/');
    if (i === -1) {
      return resource.toLowerCase();
    }
    return resource.substring(0, i).toLowerCase() + resource.substring(i);
  }
450666
function reqToJSON () {
  const {ip, method, url, headers} = this
  const userAgent = headers ? headers['user-agent'] : void (0)
  return {ip, method, url, userAgent}
}
1118563
function convertResponse(response) {
      var results = {tables: [], indexes: []};
      var i=0;
      var start=0;
      if (dbName) {
        results.db = response[0];
        start++;
        i++;
      }
      while (i < start + tableNames.length) {
        tableName = tableNames[i-start];
        results.tables[i-start]=response[i];
        i++;
      }
      start = start + tableNames.length;
      if (tableNames.length > 0) {
        var j = 0;
        var indexNames = Object.keys(tables[tableNames[j]].indexOpts);
        var indexResults;
        indexResults = [];
        results.indexes[j] = indexResults;
        while (i < response.length) {
          indexResults[i-start] = response[i];
          i++;
          while (i-start >= indexNames.length && i < response.length){
            j++;
            indexNames = Object.keys(tables[tableNames[j]].indexOpts);
            indexResults = [];
            results.indexes[j] = indexResults;
            start = i;
          }
        }
      }
      return results;
    }
1033295
function normalizeData(data) {
  // Package.json
  if (data.buddy) data = data.buddy;
  // Handle super simple mode
  if (data.input) data = { build: [data] };
  return data;
}
762322
function normalizeRel(base, input) {
  if (!input) return;
  if (!Array.isArray(input)) input = [ input ];

  return flatten(input).map(function (rel) {
    return rel in iana ? rel : url.resolve(base, rel);
  });
}
225642
def normalize(input, case_mapping=protocol.DEFAULT_CASE_MAPPING):
    
    if case_mapping not in protocol.CASE_MAPPINGS:
        raise pydle.protocol.ProtocolViolation('Unknown case mapping ({})'.format(case_mapping))

    input = input.lower()

    if case_mapping in ('rfc1459', 'rfc1459-strict'):
        input = input.replace('{', '[').replace('}', ']').replace('|', '\\')
    if case_mapping == 'rfc1459':
        input = input.replace('~', '^')

    return input
412565
function(dbresult) {
        // start with response header
        var jsonresponse= // validate syntaxe at http://geojsonlint.com/
          {"type":"GeometryCollection"
          ,"device":
            {"type":"Device"
            ,"class":device.class
            ,"model": device.model
            ,"call": device.call
          },"properties":
            {"type":"Properties"
            ,'id'  : query.devid
            ,"name": device.name
            ,'url': devurl
            ,'img': device.img
          }
          ,"geometries":[]             
          };       
     
        for (var idx in dbresult) {
            var pos = dbresult [idx];
            var ptsinfo=util.format ("%s<br>Position:[%s,%s] Speed:%s",pos.date,pos.lon.toFixed(4),pos.lat.toFixed(4),pos.sog.toFixed(1));
            jsonresponse.geometries.push (
                   {'type':'Point'
                    ,'coordinates' :[pos.lon, pos.lat]
                    ,'sog' : pos.sog
                    ,'cog' : pos.cog
                    ,'date' : pos.date.getTime()
                    ,'properties'  :
                        {'type':'Properties'
                        ,"title": ptsinfo 
                    }});
           };
    if (query.jsoncallback === undefined) {
        response.writeHead(200,{"Content-Type": "application/json"});  
        response.write(JSON.stringify(jsonresponse));
    } else {
        response.writeHead(200,{"Content-Type": "text/javascript",'Cache-Control':'no-cache'});  
        var fakescript=query.jsoncallback +'(' + JSON.stringify(jsonresponse) +');';
        response.write (fakescript);
    }      
    response.end(); 
    }
601985
def normalize_response_value(rv):
    
    status = headers = None
    if isinstance(rv, tuple):
        rv, status, headers = rv + (None,) * (3 - len(rv))
    return rv, status, headers
971125
def _ok(self, packets=None, headers=None, b64=False):
        """"""
        if packets is not None:
            if headers is None:
                headers = []
            if b64:
                headers += [('Content-Type', 'text/plain; charset=UTF-8')]
            else:
                headers += [('Content-Type', 'application/octet-stream')]
            return {'status': '200 OK',
                    'headers': headers,
                    'response': payload.Payload(packets=packets).encode(b64)}
        else:
            return {'status': '200 OK',
                    'headers': [('Content-Type', 'text/plain')],
                    'response': b'OK'}