Read a notebook from a string
344146
def reads(text, fmt, as_version=4, **kwargs):
    """"""
    fmt = copy(fmt)
    fmt = long_form_one_format(fmt)
    ext = fmt['extension']

    if ext == '.ipynb':
        return nbformat.reads(text, as_version, **kwargs)

    format_name = read_format_from_metadata(text, ext) or fmt.get('format_name')

    if format_name:
        format_options = {}
    else:
        format_name, format_options = guess_format(text, ext)

    if format_name:
        fmt['format_name'] = format_name

    fmt.update(format_options)
    reader = TextNotebookConverter(fmt)
    notebook = reader.reads(text, **kwargs)
    rearrange_jupytext_metadata(notebook.metadata)

    if format_name and insert_or_test_version_number():
        notebook.metadata.setdefault('jupytext', {}).setdefault('text_representation', {}).update(
            {'extension': ext, 'format_name': format_name})

    return notebook
721825
def from_string(cls, s):
        

        log.debug("Parsing email from string")
        message = email.message_from_string(s)
        return cls(message)
1249849
def from_string(string):
        
        lines = list(clean_lines(string.splitlines()))
        params = {}
        for line in lines:
            for sline in line.split(';'):
                m = re.match(r'(\w+)\s*=\s*(.*)', sline.strip())
                if m:
                    key = m.group(1).strip()
                    val = m.group(2).strip()
                    val = Incar.proc_val(key, val)
                    params[key] = val
        return Incar(params)
1228921
def from_string(cls, s):
        """"""
        for num, text in cls._STATUS2STR.items():
            if text == s:
                return cls(num)
        else:
            raise ValueError("Wrong string %s" % s)
1261991
def from_string(cls, s):
        
        # Extract num and unit string.
        s = s.strip()
        for i, char in enumerate(s):
            if char.isalpha() or char.isspace():
                break
        else:
            raise Exception("Unit is missing in string %s" % s)
        num, unit = float(s[:i]), s[i:]

        # Find unit type (set it to None if it cannot be detected)
        for unit_type, d in BASE_UNITS.items():
            if unit in d:
                break
        else:
            unit_type = None

        return cls(num, unit, unit_type=unit_type)
275297
def read_string(cls, string):
        
        if PY3 and not isinstance(string, byte_types):
            string = string.encode()

        return cls.decode(string)
968080
def from_string(proto_str):
    '''
    
    '''
    _, proto_file = tempfile.mkstemp(suffix='.proto')

    with open(proto_file, 'w+') as proto_f:
        proto_f.write(proto_str)

    return from_file(proto_file)
411816
def _parse_from_string(string_input):
        
        # Check if comment line is present.
        read_lines = list(filter(None, string_input.split('\n')))
        if read_lines[0].startswith('#'):
            comment = read_lines.pop(0)
        else:
            comment = ''

        if len(read_lines) > 1:
            # Assume that Sudoku is defined over several rows.
            order = int(math.sqrt(len(read_lines)))
        else:
            # Sudoku is defined on one line.
            order = int(math.sqrt(math.sqrt(len(read_lines[0]))))
            read_lines = filter(lambda x: len(x) == (order ** 2), [read_lines[0][i:(i + order ** 2)] for
                                i in utils.range_(len(read_lines[0])) if i % (order ** 2) == 0])
        matrix = utils.get_list_of_lists(
            order ** 2, order ** 2, fill_with=0)

        for i, line in enumerate(read_lines):
            line = line.strip()
            for j, value in enumerate(line):
                if value.isdigit() and int(value):
                    matrix[i][j] = int(value)
                else:
                    matrix[i][j] = 0
        return order, comment, matrix
415590
def read_string(self):
        """"""
        length = self._stream.read_var_uint32()
        return self._stream.read_string(length)
1342736
def from_string(cls, string):
        """"""
        if string is None:
            string = ''

        if not isinstance(string, six.string_types):
            raise TypeError('string has to be a string type, got: {}'.format(type(string)))

        dictionary = {}
        tokens = [token.strip() for token in shlex.split(string)]

        def list_tuples(some_iterable):
            items, nexts = itertools.tee(some_iterable, 2)
            nexts = itertools.chain(itertools.islice(nexts, 1, None), [None])
            return list(zip(items, nexts))

        for token_current, token_next in list_tuples(tokens):

            # If current token starts with a dash, it is a value so we skip it
            if not token_current.startswith('-'):
                continue

            # If the next token is None or starts with a dash, the current token must be a flag, so the value is True
            if not token_next or token_next.startswith('-'):
                dictionary[token_current.lstrip('-')] = True

            # Otherwise the current token is an option with the next token being its value
            else:
                dictionary[token_current.lstrip('-')] = token_next

        return cls.from_dictionary(dictionary)
645908
def from_string(line):
        
        result = StringValueMap()
        
        if line == None or len(line) == 0:
            return result

        tokens = str(line).split(';')
        for token in tokens:
            if len(token) == 0:
                continue
            index = token.find('=')
            key = token[0:index] if index >= 0 else token
            value = token[index + 1:] if index >= 0 else None
            result.put(key, value)

        return result
172402
def script_string_to_notebook(str, pth):
    

    nb = py2jn.py_string_to_notebook(str)
    py2jn.write_notebook(nb, pth)
378561
def import_from_string(value):
    """"""
    value = value.replace('-', '_')
    try:
        module_path, class_name = value.rsplit('.', 1)
        module = import_module(module_path)
        return getattr(module, class_name)
    except (ImportError, AttributeError) as ex:
        raise ImportError("Could not import '{}'. {}: {}.".format(
            value, ex.__class__.__name__, ex))
461130
def md_to_notebook(text):
    """"""
    tmp_file = tempfile.NamedTemporaryFile(delete=False)
    tmp_file.write(text.encode('utf-8'))
    tmp_file.close()

    pandoc(u'--from markdown --to ipynb -s --atx-headers --wrap=preserve --preserve-tabs', tmp_file.name, tmp_file.name)

    with open(tmp_file.name, encoding='utf-8') as opened_file:
        notebook = ipynb_reads(opened_file.read(), as_version=4)
    os.unlink(tmp_file.name)

    return notebook
693881
def read_string(self):
        
        length = self.read_int()
        return str(self.read(length).decode("UTF-8"))
218937
def read_text(forfn, nrows=None, verbose=True):
    
    """
    tqdm_prog = tqdm if verbose else no_tqdm
    nrows = wc(forfn, nrows=nrows)  # not necessary when nrows==None
    lines = np.empty(dtype=object, shape=nrows)
    with ensure_open(forfn) as f:
        for i, line in enumerate(tqdm_prog(f, total=nrows)):
            if i >= len(lines):
                break
            lines[i] = ensure_str(line).rstrip('\n').rstrip('\r')
        if all('\t' in line for line in lines):
            num_tabs = [sum([1 for c in line if c == '\t']) for line in lines]
            del lines
            if all(i == num_tabs[0] for i in num_tabs):
                f.seek(0)
                return read_csv(f, sep='\t', header=None, nrows=nrows)
        elif sum((1 for line in lines if any((tag.lower() in line.lower() for tag in HTML_TAGS)))
                ) / float(len(lines)) > .05:
            return np.array(html2text(EOL.join(lines)).split(EOL))
    return lines
1308422
def markdown_to_notebook(infile, outfile):
    """"""

    # Read infile into a string
    with open(infile, 'r') as fin:
        str = fin.read()
    # Enclose the markdown within triple quotes and convert from
    # python to notebook
    str = '"""' + str + '"""'
    nb = py2jn.py_string_to_notebook(str)
    py2jn.tools.write_notebook(nb, outfile, nbver=4)