Generate sample json data for testing
766348
def generate_sample_json():
    """"""

    check = EpubCheck(samples.EPUB3_VALID)
    with open(samples.RESULT_VALID, 'wb') as jsonfile:
        jsonfile.write(check._stdout)

    check = EpubCheck(samples.EPUB3_INVALID)
    with open(samples.RESULT_INVALID, 'wb') as jsonfile:
        jsonfile.write(check._stdout)
223220
def sample(config, samples):
  """"""
  url = get_api_path('sample.json')
  multiple_files = []
  images = [s['image'] for s in samples]
  labels = [s['label'] for s in samples]
  for image in images:
    multiple_files.append(('images', (image, open(image, 'rb'), 'image/png')))
  headers=get_headers(no_content_type=True)
  headers["config"]= json.dumps(config, cls=HCEncoder)
  headers["labels"]= json.dumps(labels)
  print("With headers", headers)

  try:
      r = requests.post(url, files=multiple_files, headers=headers, timeout=30)
      return r.text
  except requests.exceptions.RequestException:
      e = sys.exc_info()[0]
      print("Error while calling hyperchamber - ", e)
      return None
482305
def json_dumps(o):
    """"""
    return json.dumps(o, indent=4, sort_keys=True, ensure_ascii=True,
                      separators=(',', ': ')).encode('ascii')
511196
def json(self, start=None):
        
        if start is not None:
            data = self.data[start]
        return json.dumps(self.data, indent=4)
474408
def _json_data(x, extraneous):
    """"""

    if type(x) in has_json_data and has_json_data[type(x)]:
        if json_data_takes_extraneous[type(x)]:
            return x.json_data(extraneous=extraneous)
        else:
            return x.json_data()
    else:
        htj = hasattr(x, "json_data") and callable(x.json_data)
        has_json_data[type(x)] = htj
        if htj:
            argspec = inspect.getargspec(x.json_data)
            tjte = 'extraneous' in argspec.args or argspec.keywords
            json_data_takes_extraneous[type(x)] = tjte
            if tjte:
                return x.json_data(extraneous=extraneous)
            else:
                return x.json_data()
        else:
            return to_json(x, extraneous)
192577
def parse_json(data):
    
    sample_rate = data['datarate']
    unit = data['units']
    dtype = CIS_DATA_TYPE[data['datatype']]
    model = data['source']
    url = data['displayurl']
    return Channel(data['name'], sample_rate=sample_rate, unit=unit,
                   dtype=dtype, model=model, url=url)
973915
def get_samples_data(self):
        
        for obj in self.get_samples_from_request():
            yield {
                "obj": obj,
                "id": api.get_id(obj),
                "uid": api.get_uid(obj),
                "title": api.get_title(obj),
                "path": api.get_path(obj),
                "url": api.get_url(obj),
                "sample_type": obj.getSampleTypeTitle(),
                "client_title": obj.getClientTitle(),
                "date": ulocalized_time(obj.created(), long_format=True),
            }
335014
def execute(self, input_data):
        '''  '''
        raw_bytes = input_data['sample']['raw_bytes']
        zipfile_output = zipfile.ZipFile(StringIO(raw_bytes))
        payload_md5s = []
        for name in zipfile_output.namelist():
            filename = os.path.basename(name)
            payload_md5s.append(self.workbench.store_sample(zipfile_output.read(name), name, 'unknown'))
        return {'payload_md5s': payload_md5s}
595379
def as_json(opts={})
      atts = {
        'id'                => id,
        'color'             => color,
        'status'            => display_status,
        'percent_complete'  => percent_complete,
        'work_units'        => work_units.count,
        'time_taken'        => time_taken
      }
      atts['outputs'] = JSON.parse(outputs) if outputs
      atts['email']   = email               if email
      atts
    end
527262
def generate_ini(self):
        
        example = []
        example.append("[settings]")
        for key in sorted(list(self.spec.keys())):
            if self.spec[key]['type'] in [list, dict]:
                value = json.dumps(self.spec[key].get('example', ''))
            else:
                value = self.spec[key].get('example', '')
            string = f"{key.lower()}={value}"
            example.append(string)
        print("\n".join(example))
1214069
def json_dumps(obj):
    
    try:
        return json.dumps(obj, indent=2, sort_keys=True, allow_nan=False)
    except ValueError:
        pass
    # we don't want to call do_map on the original object since it can
    # contain objects that need to be converted for JSON. after reading
    # in the created JSON we get a limited set of possible types we
    # can encounter
    json_str = json.dumps(obj, indent=2, sort_keys=True, allow_nan=True)
    json_obj = json.loads(json_str)

    def do_map(obj):
        if obj is None:
            return None
        if isinstance(obj, basestring):
            return obj
        if isinstance(obj, dict):
            res = {}
            for (key, value) in obj.items():
                res[key] = do_map(value)
            return res
        if isinstance(obj, collections.Iterable):
            res = []
            for el in obj:
                res.append(do_map(el))
            return res
        # diverging numbers need to be passed as strings otherwise it
        # will throw a parsing error on the ECMAscript consumer side
        if math.isnan(obj):
            return "NaN"
        if math.isinf(obj):
            return "Infinity" if obj > 0 else "-Infinity"
        return obj

    return json.dumps(
        do_map(json_obj), indent=2, sort_keys=True, allow_nan=False)
47479
def parse_sample_data(sample_data, module_name):
    
    samples = {}
    for index, chunk in enumerate(sample_data.split("\n\n")):
        chunk = "{}-{}-{}".format(module_name, index, chunk)
        name, sample = re.split("-?\n", chunk, 1)
        try:
            samples[name] = ast.literal_eval(sample)
        except SyntaxError:
            samples[name] = SAMPLE_DATA_ERROR
    return samples
819971
def json_dumps(self, data):
        
        return json.dumps(
            data, 
            separators=(',', ':'), 
            sort_keys=True, 
            cls=self.json_encoder, 
            ensure_ascii=False
        ).encode('utf8')
1154939
def _dump_json(self, data, new_line=False):
        

        # We do not want any spaces between keys and values in JSON
        json_data = json.dumps(data, separators=(',', ':'))

        if new_line:
            json_data = "%s\n" % json_data

        # Generate sha256sum of the JSON data, may be handy
        sha = hashlib.sha256(json_data.encode('utf-8')).hexdigest()

        return json_data, sha
167216
function createSamples(src) {
  var result = [];

  src
    .replace(/…/, '')
    .trim()
    .replace(/,$/, '')
    .split(',')
    .map(function (val) { return val.trim(); })
    .forEach(function (val) {
      if (val.indexOf('~') !== -1) {
        result = result.concat(fillRange(val));
      } else {
        // push test data as String
        result.push(val);
        // push test data as Number if the same
        if (String(+val) === val) { result.push(+val); }
      }
    });

  return result;
}
1027919
def render_json(result, cfg, **kwargs):
    
    result = json.loads(result.decode('utf-8'))
    head = result['head']
    if 'results' not in result:
        if 'boolean' in result:
            r = u'Result: {}'.format(result['boolean'])
        else:
            r = u'Unsupported result: \n' + unicode(result)
        return {'data': {'text/plain': r},
                'metadata': {}}

    vars = head['vars']
    nrow = len(result['results']['bindings'])
    if cfg.dis == 'table':
        j = json_iterator(vars, result['results']['bindings'], set(cfg.lan),
                          add_vtype=cfg.typ)
        n, data = html_table(j, limit=cfg.lmt, withtype=cfg.typ)
        data += div('Total: {}, Shown: {}', nrow, n, css="tinfo")
        data = {'text/html': div(data)}
    else:
        result = json.dumps(result,
                            ensure_ascii=False, indent=2, sort_keys=True)
        data = {'text/plain': unicode(result)}

    return {'data': data,
            'metadata': {}}
745178
def generate_sbi_json(num_pbs: int = 3, project: str = 'sip',
                      programme_block: str = 'sip_demos',
                      pb_config: Union[dict, List[dict]] = None,
                      workflow_config:
                      Union[dict, List[dict]] = None,
                      register_workflows=True) -> str:
    """"""
    return json.dumps(generate_sbi_config(num_pbs, project, programme_block,
                                          pb_config,
                                          workflow_config, register_workflows))