Convert a python script represented as string `str` to a notebook
    with filename `pth`.
172402
def script_string_to_notebook(str, pth):
    

    nb = py2jn.py_string_to_notebook(str)
    py2jn.write_notebook(nb, pth)
824611
def make_example_scripts_docs(spth, npth, rpth):
    

    # Ensure that output directory exists
    mkdir(rpth)

    # Iterate over index files
    for fp in glob(os.path.join(spth, '*.rst')) + \
              glob(os.path.join(spth, '*', '*.rst')):
        # Index basename
        b = os.path.basename(fp)
        # Index dirname
        dn = os.path.dirname(fp)
        # Name of subdirectory of examples directory containing current index
        sd = os.path.split(dn)
        # Set d to the name of the subdirectory of the root directory
        if dn == spth:  # fp is the root directory index file
            d = ''
        else:           # fp is a subdirectory index file
            d = sd[-1]
        # Path to corresponding subdirectory in docs directory
        fd = os.path.join(rpth, d)
        # Ensure notebook subdirectory exists
        mkdir(fd)
        # Filename of index file to be constructed
        fn = os.path.join(fd, b)
        # Process current index file if corresponding notebook file
        # doesn't exist, or is older than index file
        if update_required(fp, fn):
            print('Converting %s                ' % os.path.join(d, b),
                  end='\r')
            # Convert script index to docs index
            rst_to_docs_rst(fp, fn)

    # Iterate over example scripts
    for fp in sorted(glob(os.path.join(spth, '*', '*.py'))):
        # Name of subdirectory of examples directory containing current script
        d = os.path.split(os.path.dirname(fp))[1]
        # Script basename
        b = os.path.splitext(os.path.basename(fp))[0]
        # Path to corresponding notebook
        fn = os.path.join(npth, d, b + '.ipynb')
        # Path to corresponding sphinx doc file
        fr = os.path.join(rpth, d, b + '.rst')
        # Only proceed if script and notebook exist
        if os.path.exists(fp) and os.path.exists(fn):
            # Convert notebook to rst if notebook is newer than rst
            # file or if rst file doesn't exist
            if update_required(fn, fr):
                fnb = os.path.join(d, b + '.ipynb')
                print('Processing %s                ' % fnb, end='\r')
                script_and_notebook_to_rst(fp, fn, fr)
        else:
            print('WARNING: script %s or notebook %s not found' %
                  (fp, fn))
744544
def make_sh_output_script(script_string, witness=False):
    '''
    
    '''
    if witness and not riemann.network.SEGWIT:
        raise ValueError(
            'Network {} does not support witness scripts.'
            .format(riemann.get_current_network_name()))

    script_bytes = serialization.serialize(script_string)
    return make_sh_script_pubkey(script_bytes=script_bytes, witness=witness)
52284
def notebook_to_md(notebook):
    """"""
    tmp_file = tempfile.NamedTemporaryFile(delete=False)
    tmp_file.write(ipynb_writes(notebook).encode('utf-8'))
    tmp_file.close()

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

    with open(tmp_file.name, encoding='utf-8') as opened_file:
        text = opened_file.read()

    os.unlink(tmp_file.name)
    return '\n'.join(text.splitlines())
900577
def get_script_str(self, reset=True):
        """"""
        s = "\n".join(l for l in self._lines)
        if reset:
            self.reset()
        return s
1350951
def packstr(instr, textwidth=160, breakchars=' ', break_words=True,
            newline_prefix='', indentation='', nlprefix=None, wordsep=' ',
            remove_newlines=True):
    
    if not isinstance(instr, six.string_types):
        instr = repr(instr)
    if nlprefix is not None:
        newline_prefix = nlprefix
    str_ = pack_into(instr, textwidth, breakchars, break_words, newline_prefix,
                     wordsep, remove_newlines)
    if indentation != '':
        str_ = indent(str_, indentation)
    return str_
1100547
def py(sfn, string=False, **kwargs):  # pylint: disable=C0103
    '''
    
    '''
    if not os.path.isfile(sfn):
        return {}

    base_fname = os.path.basename(sfn)
    name = base_fname.split('.')[0]

    if USE_IMPORTLIB:
        # pylint: disable=no-member
        loader = importlib.machinery.SourceFileLoader(name, sfn)
        spec = importlib.util.spec_from_file_location(name, sfn, loader=loader)
        if spec is None:
            raise ImportError()
        mod = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(mod)
        # pylint: enable=no-member
        sys.modules[name] = mod
    else:
        mod = imp.load_source(name, sfn)

    # File templates need these set as __var__
    if '__env__' not in kwargs and 'saltenv' in kwargs:
        setattr(mod, '__env__', kwargs['saltenv'])
        builtins = ['salt', 'grains', 'pillar', 'opts']
        for builtin in builtins:
            arg = '__{0}__'.format(builtin)
            setattr(mod, arg, kwargs[builtin])

    for kwarg in kwargs:
        setattr(mod, kwarg, kwargs[kwarg])

    try:
        data = mod.run()
        if string:
            return {'result': True,
                    'data': data}
        tgt = salt.utils.files.mkstemp()
        with salt.utils.files.fopen(tgt, 'w+') as target:
            target.write(salt.utils.stringutils.to_str(data))
        return {'result': True,
                'data': tgt}
    except Exception:
        trb = traceback.format_exc()
        return {'result': False,
                'data': trb}
191754
def str_to_class(s):
    """"""
    lst = s.split(".")
    klass = lst[-1]
    mod_list = lst[:-1]
    module = ".".join(mod_list)
    try:
        mod = __import__(module)
        if hasattr(mod, klass):
            return getattr(mod, klass)
        else:
            return None
    except ImportError:
        return None
1060304
def string_build(self, data, modname="", path=None):
        """"""
        module = self._data_build(data, modname, path)
        module.file_bytes = data.encode("utf-8")
        return self._post_build(module, "utf-8")
995911
def _str_to_windows(self, input_str, window_length, curse_forward):
        
        windows = []

        i = 0
        len_input = len(input_str)
        while i < len_input:
            window_text = input_str[i:i+window_length]

            if self.sanitize_input:
                windows.append({
                                    'sanitized' : self._sanitize(window_text),
                                    'text' : window_text
                                })
            else:
                windows.append({
                                    'text' : window_text
                                })

            i = i + curse_forward


        return windows
255504
def _to_str(s):
    
    if sys.version_info[0] == 2 and not isinstance(s, str):
        # Assume it's Unicode, as that's what the PEP says
        # should be provided.
        return s.encode(sys.getfilesystemencoding())
    return s
1285605
def p_program_tokenstring(p):
    
    try:
        tmp = [str(x()) if isinstance(x, MacroCall) else x for x in p[1]]
    except PreprocError as v:
        error(v.lineno, v.message)

    tmp.append(p[2])
    p[0] = tmp
1216480
def to_str(self, s):
        '''
        
        '''
        if s.__class__ != str:
            if not IS_PY3K:
                s = s.encode('utf-8')
            else:
                raise AssertionError('Expected to have str on Python 3. Found: %s (%s)' % (s, s.__class__))
        return s
1172351
def string_result(result, func, arguments):
    
    if result:
        # make a python string copy
        s = bytes_to_str(ctypes.string_at(result))
        # free original string ptr
        libvlc_free(result)
        return s
    return None
833040
def fs_str(string):
    

    if isinstance(string, str):
        return string
    assert not isinstance(string, bytes)
    return string.encode(_fs_encoding)
698896
def construct_notebook_index(title, pthlst, pthidx):
    

    # Insert title text
    txt = '"""\n## %s\n"""\n\n"""' % title
    # Insert entry for each item in pthlst
    for pth in pthlst:
        # If pth refers to a .py file, replace .py with .ipynb, otherwise
        # assume it's a directory name and append '/index.ipynb'
        if pth[-3:] == '.py':
            link = os.path.splitext(pth)[0] + '.ipynb'
        else:
            link = os.path.join(pth, 'index.ipynb')
        txt += '- [%s](%s)\n' % (pthidx[pth], link)
    txt += '"""'
    return txt
897729
def filename_to_str(self, filename):
        '''
        
        '''
        if filename.__class__ != str:
            if not IS_PY3K:
                filename = filename.encode(file_system_encoding)
            else:
                raise AssertionError('Expected to have str on Python 3. Found: %s (%s)' % (filename, filename.__class__))
        return filename