Read input from <bedfile>, set the width of all entries to <width> and 
    write the result to <outfile>.
    Input file needs to be in BED or WIG format.
13945
def write_equalwidth_bedfile(bedfile, width, outfile):
    """"""

    BUFSIZE = 10000
    f = open(bedfile)
    out = open(outfile, "w")
    lines = f.readlines(BUFSIZE)
    line_count = 0
    while lines:
        for line in lines:
            line_count += 1
            if not line.startswith("#") and not line.startswith("track") and not line.startswith("browser"):
                vals = line.strip().split("\t")
                try:
                    start, end = int(vals[1]), int(vals[2])
                except ValueError:
                    print("Error on line %s while reading %s. Is the file in BED or WIG format?" % (line_count, bedfile))
                    sys.exit(1)

                start = (start + end) // 2 - (width // 2)
                # This shifts the center, but ensures the width is identical... maybe not ideal
                if start < 0:
                    start = 0
                end = start + width
                # Keep all the other information in the bedfile if it's there
                if len(vals) > 3:
                    out.write("%s\t%s\t%s\t%s\n" % (vals[0], start, end, "\t".join(vals[3:])))
                else:
                    out.write("%s\t%s\t%s\n" % (vals[0], start, end))
        lines = f.readlines(BUFSIZE)
    
    out.close()
    f.close()
849880
def read_entry(self):
    
    if len(self.bedarray) <= self.curr_ind: return None
    val = self.bedarray[self.curr_ind]
    self.curr_ind += 1
    return val
686253
private void readSpaceSecondary(boolean prologWS)
        throws XMLStreamException
    {
        /* Let's not bother optimizing input. However, we can easily optimize
         * output, since it's easy to do, yet has more effect on performance
         * than localizing input variables.
         */
        char[] outBuf = mTextBuffer.getCurrentSegment();
        int outPtr = mTextBuffer.getCurrentSegmentSize();

        while (true) {
            if (mInputPtr >= mInputEnd) {
                /* 07-Oct-2005, TSa: Let's not throw an exception yet --
                 *   can return SPACE, and let exception be thrown
                 *   when trying to fetch next event.
                 */
                if (!loadMore()) {
                    break;
                }
            }
            char c = mInputBuffer[mInputPtr];
            if (c > CHAR_SPACE) { // end of WS?
                break;
            }
            ++mInputPtr;
            if (c == '\n') {
                markLF();
            } else if (c == '\r') {
                if (skipCRLF(c)) {
                    if (!mNormalizeLFs) {
                        // Special handling, to output 2 chars at a time:
                        outBuf[outPtr++] = c;
                        if (outPtr >= outBuf.length) { // need more room?
                            outBuf = mTextBuffer.finishCurrentSegment();
                            outPtr = 0;
                        }
                    }
                    c = '\n';
                } else if (mNormalizeLFs) {
                    c = '\n'; // For Mac text
                }
            } else if (c != CHAR_SPACE && c != '\t') {
                throwInvalidSpace(c);
            }
                
            // Ok, let's add char to output:
            outBuf[outPtr++] = c;

            // Need more room?
            if (outPtr >= outBuf.length) {
                outBuf = mTextBuffer.finishCurrentSegment();
                outPtr = 0;
            }
        }
        mTextBuffer.setCurrentLength(outPtr);
    }
371400
def bed_writer(parser, keep, extract, args):
    """"""
    # The output bed and bim file
    bim_fn = args.output + ".bim"
    with open(bim_fn, "w") as bim, PyPlink(args.output, "w") as bed:
        # Getting the samples
        samples = np.array(parser.get_samples(), dtype=str)
        k = _get_sample_select(samples=samples, keep=keep)

        # Writing the FAM file
        with open(args.output + ".fam", "w") as fam:
            for sample in samples[k]:
                print(sample, sample, "0", "0", "0", "-1", sep=" ", file=fam)

        # Getting the data generator
        generator = _get_generator(parser=parser, extract=extract, keep=k,
                                   check_maf=args.maf)

        # The number of markers extracted
        nb_extracted = 0

        for data in generator:
            # Keeping only the required genotypes, changing NaN to -1 and
            # rounding to get a hard call
            genotypes = data.genotypes
            genotypes[np.isnan(genotypes)] = -1
            genotypes = np.round(genotypes, 0)

            # Writing the genotypes and the BIM file
            bed.write_genotypes(genotypes)
            print(
                _PLINK_CHROM_ENCODE.get(str(data.variant.chrom),
                                        data.variant.chrom),
                data.variant.name, "0", data.variant.pos, data.coded,
                data.reference, sep="\t", file=bim,
            )
            nb_extracted += 1

        if nb_extracted == 0:
            logger.warning("No markers matched the extract list")
1289674
def init_write_line(self):
        """"""
        format_list = self._format_list
        output_info = self.gen_output_fmt(format_list)
        self._output_fmt = "".join([sub[0] for sub in output_info])
        self._out_gen_fmt = [sub[1] for sub in output_info if sub[1] is not None]
        self._out_widths = [sub[2] for sub in output_info if sub[2] is not None]
        self._write_line_init = True
840422
def ainput(prompt='', *, streams=None, use_stderr=False, loop=None):
    """"""
    # Get standard streams
    if streams is None:
        streams = yield from get_standard_streams(
            use_stderr=use_stderr, loop=loop)
    reader, writer = streams
    # Write prompt
    writer.write(prompt.encode())
    yield from writer.drain()
    # Get data
    data = yield from reader.readline()
    # Decode data
    data = data.decode()
    # Return or raise EOF
    if not data.endswith('\n'):
        raise EOFError
    return data.rstrip('\n')
1164013
def _bed_to_bed6(orig_file, out_dir):
    
    bed6_file = os.path.join(out_dir, "%s-bed6%s" % os.path.splitext(os.path.basename(orig_file)))
    if not utils.file_exists(bed6_file):
        with open(bed6_file, "w") as out_handle:
            for i, region in enumerate(list(x) for x in pybedtools.BedTool(orig_file)):
                region = [x for x in list(region) if x]
                fillers = [str(i), "1.0", "+"]
                full = region + fillers[:6 - len(region)]
                out_handle.write("\t".join(full) + "\n")
    return bed6_file
1004920
function decompressOutput(output, br) {
  output.value = br.readVarint();
  decompressScript(output.script, br);
  return output;
}
723000
def bed(args):
    
    p = OptionParser(bed.__doc__)
    opts, args = p.parse_args(args)

    if len(args) != 1:
        sys.exit(not p.print_help())

    idsfile, = args
    ids = set(x.strip() for x in open(idsfile))
    data = get_bed_from_phytozome(list(ids))

    pf = idsfile.rsplit(".", 1)[0]
    bedfile = pf + ".bed"
    fw = open(bedfile, "w")
    for i, row in enumerate(data):
        row = row.strip()
        if row == "":
            continue

        print(row, file=fw)

    logging.debug("A total of {0} records written to `{1}`.".format(i + 1, bedfile))
833992
def writef(notebook, nb_file, fmt=None):
    """"""
    if nb_file == '-':
        write(notebook, sys.stdout, fmt)
        return

    _, ext = os.path.splitext(nb_file)
    fmt = copy(fmt or {})
    fmt = long_form_one_format(fmt, update={'extension': ext})

    create_prefix_dir(nb_file, fmt)

    with io.open(nb_file, 'w', encoding='utf-8') as stream:
        write(notebook, stream, fmt)
232442
def _line_to_entry(self,line):
    """"""
    f = line.rstrip().split("\t")
    """
    'chrom'
    'chromStart'
    'chromEnd'
    'name'
    'score'
    'strand'
    'thickStart'
    'thickEnd'
    'itemRgb'
    'blockCount'
    'blockSizes'
    'blockStarts'
    """
    return Bed12Fields(
       f[0],
       int(f[1]),
       int(f[2]),
       f[3],
       int(f[4]),
       f[5],
       int(f[6]),
       int(f[7]),
       [int(x) for x in f[8].rstrip(',').split(',')],
       int(f[9]),
       [int(x) for x in f[10].rstrip(',').split(',')],
       [int(x) for x in f[11].rstrip(',').split(',')])
1127384
def decomment(bed_file, out_file):
    
    if file_exists(out_file):
        return out_file

    with utils.open_gzipsafe(bed_file) as in_handle, open(out_file, "w") as out_handle:
        for line in in_handle:
            if line.startswith("#") or line.startswith("browser") or line.startswith("track"):
                continue
            else:
                out_handle.write(line)
    return out_file
231663
def bed(args):
    '''
    
    '''
    from jcvi.utils.cbook import gene_name

    p = OptionParser(bed.__doc__)
    p.add_option("--type", dest="type", default="gene",
            help="Feature type to extract, use comma for multiple [default: %default]")
    p.add_option("--key", default="ID", help="Key in the attributes to extract")
    p.add_option("--source",
            help="Source to extract from, use comma for multiple [default: %default]")
    p.add_option("--span", default=False, action="store_true",
            help="Use feature span in the score column")
    p.add_option("--score_attrib", dest="score_attrib", default=False,
            help="Attribute whose value is to be used as score in `bedline` [default: %default]")
    p.add_option("--append_source", default=False, action="store_true",
            help="Append GFF source name to extracted key value")
    p.add_option("--append_ftype", default=False, action="store_true",
            help="Append GFF feature type to extracted key value")
    p.add_option("--nosort", default=False, action="store_true",
            help="Do not sort the output bed file [default: %default]")
    p.set_stripnames(default=False)
    p.set_outfile()

    opts, args = p.parse_args(args)
    if len(args) != 1:
        sys.exit(not p.print_help())

    gffile, = args
    key = opts.key or None
    type = opts.type or set()
    source = opts.source or set()
    strip_names = opts.strip_names
    span = opts.span

    if opts.type:
        type = set(x.strip() for x in opts.type.split(","))
    if opts.source:
        source = set(x.strip() for x in opts.source.split(","))

    gff = Gff(gffile, key=key, append_source=opts.append_source, \
        append_ftype=opts.append_ftype, score_attrib=opts.score_attrib)
    b = Bed()

    for g in gff:
        if type and g.type not in type:
            continue
        if source and g.source not in source:
            continue

        bl = g.bedline
        if strip_names:
            bl.accn = gene_name(bl.accn)
        if span:
            bl.score = bl.span
        b.append(bl)

    sorted = not opts.nosort
    b.print_to_file(opts.outfile, sorted=sorted)
    logging.debug("Extracted {0} features (type={1} id={2})".\
                    format(len(b), ",".join(type), key))
952473
def write(self, word):
		
		bytes_ = int_to_bytes(word, self.width)
		self.open_stream_out.write(bytes_)
774446
def write_line(self, values):
        

        if not self._write_line_init:
            self.init_write_line()

        if len(self._out_widths) > len(values):
            raise For2PyError(f"ERROR: too few values for format {self._format_list}\n")

        out_strs = []
        for i in range(len(self._out_widths)):
            out_fmt = self._out_gen_fmt[i]
            out_width = self._out_widths[i]

            out_val = out_fmt.format(values[i])
            if len(out_val) > out_width:  # value too big for field
                out_val = "*" * out_width

            out_strs.append(out_val)

        out_str_exp = (
            '"' + self._output_fmt + '".format' + str(tuple(out_strs))
        )
        out_str = eval(out_str_exp)
        return out_str + "\n"
403494
def columnize(items, width=None, file=sys.stdout):
    
    if not items:
        return
    if width is None:
        width = shutil.get_terminal_size()[0] if file is sys.stdout else 80
    items = [rendering.vtmlrender(x) for x in items]
    maxcol = max(items, key=len)
    colsize = len(maxcol) + 2
    cols = width // colsize
    if cols < 2:
        for x in items:
            print(x, file=file)
        return
    lines = math.ceil(len(items) / cols)
    for i in range(lines):
        row = items[i:None:lines]
        print(*[x.ljust(colsize) for x in row], sep='', file=file)
7866
def ptconcat(output_file, input_files, overwrite=False):
    """"""
    filt = tb.Filters(
        complevel=5, shuffle=True, fletcher32=True, complib='zlib'
    )
    out_tabs = {}
    dt_file = input_files[0]
    log.info("Reading data struct '%s'..." % dt_file)
    h5struc = tb.open_file(dt_file, 'r')
    log.info("Opening output file '%s'..." % output_file)
    if overwrite:
        outmode = 'w'
    else:
        outmode = 'a'
    h5out = tb.open_file(output_file, outmode)

    for node in h5struc.walk_nodes('/', classname='Table'):
        path = node._v_pathname
        log.debug(path)
        dtype = node.dtype
        p, n = os.path.split(path)
        out_tabs[path] = h5out.create_table(
            p, n, description=dtype, filters=filt, createparents=True
        )
    h5struc.close()
    for fname in input_files:
        log.info('Reading %s...' % fname)
        h5 = tb.open_file(fname)
        for path, out in out_tabs.items():
            tab = h5.get_node(path)
            out.append(tab[:])
        h5.close()
    h5out.close()