Parse a notebook .ipynb file.

        Parameters
        ----------
        json_data : file
            A file handle for an .ipynb file.

        Returns
        -------
        nb : An IPython Notebook data structure.
760802
def parse(self, json_data):
        
        data = current.read(json_data, 'ipynb')
        json_data.close()
        return data
1242147
def parse_json(json_file):
    
    if not os.path.exists(json_file):
        return None

    try:
        with open(json_file, "r") as f:
            info_str = f.readlines()
            info_str = "".join(info_str)
            json_info = json.loads(info_str)
            return unicode2str(json_info)
    except BaseException as e:
        logging.error(e.message)
        return None
278868
def convert_ipynb_to_gallery(file_name):
    
    python_file = ""

    nb_dict = json.load(open(file_name))
    cells = nb_dict['cells']

    for i, cell in enumerate(cells):
        if i == 0:
            assert cell['cell_type'] == 'markdown', \
                'First cell has to be markdown'

            md_source = ''.join(cell['source'])
            rst_source = pdoc.convert_text(md_source, 'rst', 'md')
            python_file = '"""\n' + rst_source + '\n"""'
        else:
            if cell['cell_type'] == 'markdown':
                md_source = ''.join(cell['source'])
                rst_source = pdoc.convert_text(md_source, 'rst', 'md')
                commented_source = '\n'.join([
                    '# ' + x for x in rst_source.split('\n')
                ])
                python_file = python_file + '\n\n\n' + '#' * 70 + '\n' + \
                    commented_source
            elif cell['cell_type'] == 'code':
                source = ''.join(cell['source'])
                python_file = python_file + '\n' * 2 + source

    open(file_name.replace('.ipynb', '.py'), 'w').write(python_file)
398260
def iob2json(input_data, n_sents=10, *args, **kwargs):
    
    docs = []
    for group in minibatch(docs, n_sents):
        group = list(group)
        first = group.pop(0)
        to_extend = first["paragraphs"][0]["sentences"]
        for sent in group[1:]:
            to_extend.extend(sent["paragraphs"][0]["sentences"])
        docs.append(first)
    return docs
861640
def code_from_ipynb(nb, markdown=False):
    
    code = PREAMBLE
    for cell in nb['cells']:
        if cell['cell_type'] == 'code':
            # transform the input to executable Python
            code += ''.join(cell['source'])
        if cell['cell_type'] == 'markdown':
            code += '\n# ' + '# '.join(cell['source'])
        # We want a blank newline after each cell's output.
        # And the last line of source doesn't have a newline usually.
        code += '\n\n'
    return code
1241544
def from_json(data):
        
        memfiles = InMemoryFiles()
        memfiles.files = json.loads(data)
        return memfiles
386807
def update_nb_metadata(nb_path=None, title=None, summary=None, keywords='fastai', overwrite=True, **kwargs):
    ""
    nb = read_nb(nb_path)
    data = {'title': title, 'summary': summary, 'keywords': keywords, **kwargs}
    data = {k:v for (k,v) in data.items() if v is not None} # remove none values
    if not data: return
    nb['metadata']['jekyll'] = data
    write_nb(nb, nb_path)
    NotebookNotary().sign(nb)
748834
def parse_nem_file(nem_file) -> NEMFile:
    
    reader = csv.reader(nem_file, delimiter=',')
    return parse_nem_rows(reader, file_name=nem_file)
579202
def parse(string, is_file=False, obj=False):
        
        try:
            if obj is False:
                if is_file:
                    return system_json.load(string)
                return system_json.loads(string, encoding='utf8')
            else:
                if is_file:
                    return system_json.load(
                        string,
                        object_hook=lambda d: namedtuple('j', d.keys())
                        (*d.values()), ensure_ascii=False, encoding='utf8')
                return system_json.loads(
                    string,
                    object_hook=lambda d: namedtuple('j', d.keys())
                    (*d.values()), encoding='utf8')
        except (Exception, BaseException) as error:
            try:
                if current_app.config['DEBUG']:
                    raise error
            except RuntimeError as flask_error:
                raise error
            return None
91339
def json_data(self, instance, default=None):
        
        value = self.get(instance)
        if value:
            return value.output
        return value
885726
def parse_json(raw_data):
    '''  '''

    orig_data = raw_data

    # ignore stuff like tcgetattr spewage or other warnings
    data = filter_leading_non_json_lines(raw_data)

    try:
        return json.loads(data)
    except:
        # not JSON, but try "Baby JSON" which allows many of our modules to not
        # require JSON and makes writing modules in bash much simpler
        results = {}
        try:
            tokens = shlex.split(data)
        except:
            print "failed to parse json: "+ data
            raise

        for t in tokens:
            if t.find("=") == -1:
                raise errors.AnsibleError("failed to parse: %s" % orig_data)
            (key,value) = t.split("=", 1)
            if key == 'changed' or 'failed':
                if value.lower() in [ 'true', '1' ]:
                    value = True
                elif value.lower() in [ 'false', '0' ]:
                    value = False
            if key == 'rc':
                value = int(value)
            results[key] = value
        if len(results.keys()) == 0:
            return { "failed" : True, "parsed" : False, "msg" : orig_data }
        return results
69824
def excel2json(filename, non_empty_col=-1, file_contents=None):
    

    if file_contents:
        workbook = xlrd.open_workbook(file_contents=file_contents)
    else:
        workbook = xlrd.open_workbook(filename)

    start_row = 0
    ret = collections.defaultdict(list)
    fields = {}
    for name in workbook.sheet_names():
        sh = workbook.sheet_by_name(name)
        headers = []
        for col in range(len(sh.row(start_row))):
            headers.append(sh.cell(start_row, col).value)

        logging.info(u"sheet={} rows={} cols={}".format(
            name, sh.nrows, len(headers)))
        logging.info(json.dumps(headers, ensure_ascii=False))

        fields[name] = headers

        for row in range(start_row + 1, sh.nrows):
            item = {}
            rowdata = sh.row(row)
            if len(rowdata) < len(headers):
                msg = "skip mismatched row {}".format(
                    json.dumps(rowdata, ensure_ascii=False))
                logging.warning(msg)
                continue

            for col in range(len(headers)):
                value = sh.cell(row, col).value
                if type(value) in [unicode, basestring]:
                    value = value.strip()
                item[headers[col]] = value

            if non_empty_col >= 0 and not item[headers[non_empty_col]]:
                logging.debug("skip empty cell")
                continue

            ret[name].append(item)
        # stat
        logging.info(u"loaded {} {} (non_empty_col={})".format(
            filename, len(ret[name]), non_empty_col))
    return {'data': ret, 'fields': fields}
1214177
def stream_json_file(local_file):
    
    for i, line in enumerate(local_file):
        try:
            data = json.loads(line.decode('utf-8'))
            yield data
        except ValueError as e:
            logging.warning("Skipping line %d due to error: %s", i, e)
            continue
871303
def json_data(self, instance, default=None):
        
        value = self.get(instance)

        out = []
        for rel in value:
            if rel.isBroken():
                logger.warn("Skipping broken relation {}".format(repr(rel)))
                continue
            obj = rel.to_object
            out.append(api.get_url_info(obj))
        return out
1030313
def export_ipynb(self, pathname):
        

        if pathname == '-':
            nbf.write(self.nb, sys.__stdout__)
        else:
            with codecs.open(pathname, 'w', encoding='utf-8') as f:
                ret = nbf.write(self.nb, f)
                pass

        logging.info("Jupyter notebook exported to '{}'".format(pathname))
941476
def parse_json_feed_file(filename: str) -> JSONFeed:
    """"""
    with open(filename) as f:
        try:
            root = json.load(f)
        except json.decoder.JSONDecodeError:
            raise FeedJSONError('Not a valid JSON document')

    return parse_json_feed(root)
773879
def _read_json_file(self, json_file):
        

        self.log.debug("Reading '%s' JSON file..." % json_file)

        with open(json_file, 'r') as f:
            return json.load(f, object_pairs_hook=OrderedDict)