text:
"""
Create chromosome landscape plots that are similar to the ones used in soybean
and sorghum paper.
"""

import os.path as op
import sys
import logging

import numpy as np

from collections import defaultdict, OrderedDict

from jcvi.formats.sizes import Sizes
from jcvi.formats.base import BaseFile, DictFile, LineFile, must_open
from jcvi.formats.bed import Bed, bins
from jcvi.algorithms.matrix import moving_sum
from jcvi.graphics.base import (
    plt,
    Rectangle,
    CirclePolygon,
    savefig,
    ticker,
    human_readable_base,
    latex,
    markup,
    set_human_axis,
    normalize_axes,
    adjust_spines,
)
from jcvi.utils.cbook import human_size, autoscale
from jcvi.apps.base import OptionParser, ActionDispatcher

# Colors picked from Schmutz soybean genome paper using ColorPic
palette = ["#ACABD5", "#DBF0F5", "#3EA77A", "#FBF5AB", "#C162A6"] + list("rgbymck")
gray = "#CCCCCB"
Registration = {
    "Gypsy": "LTR-RT/Gypsy",
    "Copia": "LTR-RT/Copia",
    "hAT": "DNA-TE/hAT",
    "Helitron": "DNA-TE/Helitron",
    "Tourist": "DNA-TE/Tourist",
    "Introns": "Genes (introns)",
    "Exons": "Genes (exons)",
}

class BinLine(object):
    def __init__(self, row):
        args = row.split()
        self.chr = args[0]
        self.len = float(args[1])
        self.binlen = int(args[2])

    def __str__(self):
        return "\t".join(str(x) for x in (self.chr, self.len, self.binlen))

    def subtract(self, o):
        self.binlen -= o.len

class BinFile(LineFile):
    def __init__(self, filename):
        super(BinFile, self).__init__(filename)
        self.mapping = defaultdict(list)

        fp = open(filename)
        for row in fp:
            b = BinLine(row)
            self.append(b)
            chr, len, binlen = b.chr, b.len, b.binlen
            self.mapping[chr].append((len, binlen))
        fp.close()

class ChrInfoLine:
    def __init__(self, row, delimiter=","):
        args = [x.strip() for x in row.split(delimiter)]
        self.name = args[0]
        self.color = args[1]
        if len(args) > 2:
            self.new_name = args[2]
        else:
            self.new_name = self.name

class ChrInfoFile(BaseFile, OrderedDict):
    def __init__(self, filename, delimiter=","):
        super(ChrInfoFile, self).__init__(filename)
        with open(filename) as fp:
            for row in fp:
                if row[0] == "#":
                    continue
                line = ChrInfoLine(row, delimiter=delimiter)
                self[line.name] = line

class TitleInfoLine:
    def __init__(self, row, delimiter=","):
        args = [x.strip() for x in row.split(delimiter)]
        self.name = args[0]
        self.title = args[1]
        self.subtitle = None
        if len(args) > 2:
            self.subtitle = args[2]

class TitleInfoFile(BaseFile, OrderedDict):
    def __init__(self, filename, delimiter=","):
        super(TitleInfoFile, self).__init__(filename)
        with open(filename) as fp:
            for row in fp:
                if row[0] == "#":
                    continue
                line = TitleInfoLine(row, delimiter=delimiter)
                self[line.name] = line

def main():

    actions = (
        ("stack", "create landscape plot with genic/te composition"),
        ("heatmap", "similar to stack but adding heatmap"),
        ("composite", "combine line plots, feature bars and alt-bars"),
        ("multilineplot", "combine multiple line plots in one vertical stack"),
        # Related to chromosomal depth
        ("depth", "show per chromosome depth plot across genome"),
        ("mosdepth", "plot depth vs. coverage per chromosome"),
    )
    p = ActionDispatcher(actions)
    p.dispatch(globals())

def parse_distfile(filename):
    """Parse mosdepth dist.txt file. The file has contents like:

    #chr    start   end     depth   (header added here for clarity)
    chr01A  0       50000   31.00
    chr01A  50000   100000  36.00
    chr01A  100000  150000  280.00
    chr01A  150000  200000  190.00

    Args:
        filename (str): Path to the file.
    """
    from collections import defaultdict, Counter

    dists = defaultdict(Counter)
    with must_open(filename) as fp:
        for row in fp:
            chromosome, start, end, depth = row.split()
            depth = int(float(depth))
            dists[chromosome][depth] += 1
    logging.debug("Loaded {} seqids".format(len(dists)))
    return dists

def parse_groupsfile(filename):
    """Parse groupsfile, which contains the tracks to be plotted
    in the vertically stacked mosdepth plot.

    chr01A,chr01B g,m
    chr02A,chr02B g,m
    chr03A,chr03B g,m

    Args:
        filename (str): Path to the groups file.
    """
    groups = []
    with open(filename) as fp:
        for row in fp:
            chrs, colors = row.split()
            groups.append((chrs.split(","), colors.split(",")))
    logging.debug("Loaded {} groups".format(len(groups)))
    return groups

def cumarray_to_array(ar):
    """Convert cumulative array to normal array.

    Args:
        ar (List): List of numbers
    """
    ans = []
    for i, x in enumerate(ar):
        ans.append(x if i == 0 else (ar[i] - ar[i - 1]))
    return ans

def mosdepth(args):
    """
    %prog mosdepth mosdepth.global.dist.txt groups

    Plot depth vs. coverage per chromosome. Inspired by mosdepth plot. See also:
    https://github.com/brentp/mosdepth
    """
    import seaborn as sns

    sns.set_style("darkgrid")

    p = OptionParser(mosdepth.__doc__)
    p.add_option("--maxdepth", default=100, type="int", help="Maximum depth to plot")
    p.add_option(
        "--logscale", default=False, action="store_true", help="Use log-scale on depth"
    )
    opts, args, iopts = p.set_image_options(args, style="dark", figsize="6x8")

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

    # Read in datasets
    distfile, groupsfile = args
    dists = parse_distfile(distfile)
    groups = parse_groupsfile(groupsfile)
    logscale = opts.logscale

    # Construct a composite figure with N tracks indicated in the groups
    fig = plt.figure(1, (iopts.w, iopts.h))
    root = fig.add_axes([0, 0, 1, 1])

    rows = len(groups)
    ypad = 0.05
    yinterval = (1 - 2 * ypad) / (rows + 1)
    yy = 1 - ypad

    for group_idx, (chrs, colors) in enumerate(groups):
        yy -= yinterval
        ax = fig.add_axes([0.15, yy, 0.7, yinterval * 0.85])
        for c, color in zip(chrs, colors):
            cdata = dists[c].items()
            logging.debug("Importing {} records for {}".format(len(cdata), c))
            cx, cy = zip(*sorted(cdata))
            ax.plot(cx, cy, "-", color=color)
        if logscale:
            ax.set_xscale("log", basex=2)
        ax.set_xlim(1 if logscale else 0, opts.maxdepth)
        ax.get_yaxis().set_visible(False)
        if group_idx != rows - 1:
            ax.get_xaxis().set_visible(False)

        # Add legend to the right of the canvas
        label_pad = 0.02
        label_yy = yy + yinterval
        for c, color in zip(chrs, colors):
            label_yy -= label_pad
            root.text(0.92, label_yy, c, color=color, ha="center", va="center")

    root.text(
        0.1,
        0.5,
        "Proportion of bases at coverage",
        rotation=90,
        color="darkslategray",
        ha="center",
        va="center",
    )
    root.text(0.5, 0.05, "Coverage", color="darkslategray", ha="center", va="center")
    normalize_axes(root)
    adjust_spines(ax, ["bottom"], outward=True)

    pf = "mosdepth"
    image_name = pf + "." + iopts.format
    savefig(image_name, dpi=iopts.dpi, iopts=iopts)

def draw_depth(
    root,
    ax,
    bed,
    chrinfo={},
    defaultcolor="k",
    sepcolor="w",
    ylim=100,
    logscale=False,
    title=None,
    subtitle=None,
):
    """Draw depth plot on the given axes, using data from bed

    Args:
        root (matplotlib.Axes): Canvas axes
        ax (matplotlib.Axes): Axes to plot data on
        bed (Bed): Bed data from mosdepth
        chrinfo (ChrInfoFile): seqid => color, new name
        defaultcolor (str): matplotlib-compatible color for data points
        sepcolor (str): matplotlib-compatible color for chromosome breaks
        ylim (int): Upper limit of the y-axis (depth)
        title (str): Title of the figure, to the right of the axis
        subtitle (str): Subtitle of the figure, just below title
    """
    if chrinfo is None:
        chrinfo = {}
    sizes = bed.max_bp_in_chr
    seqids = chrinfo.keys() if chrinfo else sizes.keys()
    starts = {}
    ends = {}
    label_positions = []
    start = 0
    for seqid in seqids:
        if seqid not in sizes:
            continue
        starts[seqid] = start
        end = start + sizes[seqid]
        ends[seqid] = end
        label_positions.append((seqid, (start + end) / 2))
        start = end
    xsize = end

    # Extract plotting data
    data = []
    data_by_seqid = defaultdict(list)
    for b in bed:
        seqid = b.seqid
        if seqid not in starts:
            continue
        # chr01A  2000000 3000000 113.00
        x = starts[seqid] + (b.start + b.end) / 2
        y = float(b.accn)
        c = chrinfo[seqid].color if seqid in chrinfo else "k"
        data.append((x, y, c))
        data_by_seqid[seqid].append(y)

    x, y, c = zip(*data)
    ax.scatter(
        x,
        y,
        c=c,
        edgecolors="none",
        s=8,
        lw=0,
    )
    logging.debug("Obtained {} data points with depth data".format(len(data)))

    # Per seqid median
    medians = {}
    for seqid, values in data_by_seqid.items():
        c = chrinfo[seqid].color if seqid in chrinfo else defaultcolor
        seqid_start = starts[seqid]
        seqid_end = ends[seqid]
        seqid_median = np.median(values)
        medians[seqid] = seqid_median
        ax.plot(
            (seqid_start, seqid_end),
            (seqid_median, seqid_median),
            "-",
            lw=4,
            color=c,
            alpha=0.5,
        )

    # vertical lines for all the breaks
    for pos in starts.values():
        ax.plot((pos, pos), (0, ylim), "-", lw=1, color=sepcolor)

    # beautify the numeric axis
    for tick in ax.get_xticklines() + ax.get_yticklines():
        tick.set_visible(False)

    median_depth_y = 0.88
    chr_label_y = 0.08
    for seqid, position in label_positions:
        xpos = 0.1 + position * 0.8 / xsize
        c = chrinfo[seqid].color if seqid in chrinfo else defaultcolor
        newseqid = chrinfo[seqid].new_name if seqid in chrinfo else seqid
        root.text(
            xpos, chr_label_y, newseqid, color=c, ha="center", va="center", rotation=20
        )
        seqid_median = medians[seqid]
        root.text(
            xpos,
            median_depth_y,
            str(int(seqid_median)),
            color=c,
            ha="center",
            va="center",
        )

    if title:
        root.text(
            0.95,
            0.5,
            markup(title),
            color="darkslategray",
            ha="center",
            va="center",
            size=15,
        )
    if subtitle:
        root.text(
            0.95,
            0.375,
            markup(subtitle),
            color="darkslategray",
            ha="center",
            va="center",
            size=15,
        )

    ax.set_xticks([])
    ax.set_xlim(0, xsize)
    if logscale:
        ax.set_yscale("log", basey=2)
    ax.set_ylim(1 if logscale else 0, ylim)
    ax.set_ylabel("Depth")

    set_human_axis(ax)
    plt.setp(ax.get_xticklabels() + ax.get_yticklabels(), color="gray", size=10)
    normalize_axes(root)

def depth(args):
    """
    %prog depth *.regions.bed.gz

    Plot the mosdepth regions BED file. We recommend to generate this BED file
    by (please adjust the --by parameter to your required resolution):

    $ mosdepth --no-per-base --use-median --fast-mode --by 1000000 sample.wgs
    sample.bam

    Use --chrinfo to specify a colormap between seqid, desired color, and
    optionally a new name. For example:

    chr01A, #c51b7d, 1A
    chr01B, #4d9221, 1B
    ...

    Only seqids that are in the colormap will be plotted, in the order that's
    given in the file. When --colormap is not set, every seqid will be drawn in
    black.

    Can take multiple BED files as input and then plot all of them in a
    composite figure.
    """
    p = OptionParser(depth.__doc__)
    p.add_option(
        "--chrinfo", help="Comma-separated mappings between seqid, color, new_name"
    )
    p.add_option(
        "--titleinfo",
        help="Comma-separated titles mappings between filename, title",
    )
    p.add_option("--maxdepth", default=100, type="int", help="Maximum depth to show")
    p.add_option(
        "--logscale", default=False, action="store_true", help="Use log-scale on depth"
    )
    opts, args, iopts = p.set_image_options(args, style="dark", figsize="14x4")

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

    bedfiles = args
    chrinfo = ChrInfoFile(opts.chrinfo) if opts.chrinfo else {}
    titleinfo = TitleInfoFile(opts.titleinfo) if opts.titleinfo else {}

    fig = plt.figure(1, (iopts.w, iopts.h))
    root = fig.add_axes([0, 0, 1, 1])

    npanels = len(bedfiles)
    yinterval = 1.0 / npanels
    ypos = 1 - yinterval
    for bedfile in bedfiles:
        pf = op.basename(bedfile).split(".", 1)[0]
        bed = Bed(bedfile)

        panel_root = root if npanels == 1 else fig.add_axes([0, ypos, 1, yinterval])
        panel_ax = fig.add_axes([0.1, ypos + 0.2 * yinterval, 0.8, 0.65 * yinterval])
        if ypos > 0.001:
            root.plot((0, 1), (ypos, ypos), "-", lw=2, color="lightslategray")

        title = titleinfo.get(bedfile, pf.split("_", 1)[0])
        subtitle = None
        if isinstance(title, TitleInfoLine):
            subtitle = title.subtitle
            title = title.title

        draw_depth(
            panel_root,
            panel_ax,
            bed,
            chrinfo=chrinfo,
            ylim=opts.maxdepth,
            logscale=opts.logscale,
            title=title,
            subtitle=subtitle,
        )
        ypos -= yinterval

    normalize_axes(root)

    if npanels > 1:
        pf = op.commonprefix(bedfiles)
    pf = pf or "depth"
    image_name = pf + "." + iopts.format
    savefig(image_name, dpi=iopts.dpi, iopts=iopts)

def add_window_options(p):
    p.add_option("--window", default=500000, type="int", help="Size of window")
    p.add_option("--shift", default=100000, type="int", help="Size of shift")
    p.add_option("--subtract", help="Subtract bases from window")
    p.add_option(
        "--nomerge", default=False, action="store_true", help="Do not merge features"
    )

def check_window_options(opts):
    window = opts.window
    shift = opts.shift
    subtract = opts.subtract
    assert window % shift == 0, "--window must be divisible by --shift"
    logging.debug(
        "Line/stack-plot options: window={0} shift={1} subtract={2}".format(
            window, shift, subtract
        )
    )
    merge = not opts.nomerge

    return window, shift, subtract, merge

def get_beds(s, binned=False):
    return [x + ".bed" for x in s] if not binned else [x for x in s]

def get_nbins(clen, shift):
    nbins = clen / shift
    if clen % shift:
        nbins += 1
    return nbins

def linearray(binfile, chr, window, shift):
    mn = binfile.mapping[chr]
    m, n = zip(*mn)

    m = np.array(m, dtype="float")
    w = window / shift
    m = moving_sum(m, window=w)
    return m

def lineplot(ax, binfiles, nbins, chr, window, shift, color="br"):
    assert len(binfiles) <= 2, "A max of two line plots are supported"

    t = np.arange(nbins)
    bf = binfiles[0]
    m = linearray(bf, chr, window, shift)
    ax.plot(t, m, "{0}-".format(color[0]), lw=2)

    formatter = ticker.FuncFormatter(
        lambda x, pos: human_readable_base(int(x) * shift, pos)
    )
    ax.xaxis.set_major_formatter(formatter)
    for tl in ax.get_xticklabels():
        tl.set_color("darkslategray")

    label = bf.filename.split(".")[0]
    perw = "per {0}".format(human_size(window, precision=0))
    ax.set_ylabel(label + " " + perw, color=color[0])

    if len(binfiles) == 2:
        ax2 = ax.twinx()
        bf = binfiles[1]
        m = linearray(bf, chr, window, shift)
        ax2.plot(t, m, "{0}-".format(color[1]), lw=2)
        # Differentiate tick labels through colors
        for tl in ax.get_yticklabels():
            tl.set_color(color[0])
        for tl in ax2.get_yticklabels():
            tl.set_color(color[1])

        label = bf.filename.split(".")[0]
        ax2.set_ylabel(label + " " + perw, color=color[1])

    ax.set_xlim(0, nbins)

def composite(args):
    """
    %prog composite fastafile chr1

    Combine line plots, feature bars and alt-bars, different data types
    specified in options. Inputs must be BED-formatted. Three types of viz are
    currently supported:

    --lines: traditional line plots, useful for plotting feature freq
    --bars: show where the extent of features are
    --altbars: similar to bars, yet in two alternating tracks, e.g. scaffolds
    """
    from jcvi.graphics.chromosome import HorizontalChromosome

    p = OptionParser(composite.__doc__)
    p.add_option("--lines", help="Features to plot in lineplot")
    p.add_option("--bars", help="Features to plot in bars")
    p.add_option("--altbars", help="Features to plot in alt-bars")
    p.add_option(
        "--fatten",
        default=False,
        action="store_true",
        help="Help visualize certain narrow features",
    )
    p.add_option(
        "--mode",
        default="span",
        choices=("span", "count", "score"),
        help="Accumulate feature based on",
    )
    add_window_options(p)
    opts, args, iopts = p.set_image_options(args, figsize="8x5")

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

    fastafile, chr = args
    window, shift, subtract, merge = check_window_options(opts)
    linebeds, barbeds, altbarbeds = [], [], []
    fatten = opts.fatten
    if opts.lines:
        lines = opts.lines.split(",")
        linebeds = get_beds(lines)
    if opts.bars:
        bars = opts.bars.split(",")
        barbeds = get_beds(bars)
    if opts.altbars:
        altbars = opts.altbars.split(",")
        altbarbeds = get_beds(altbars)

    linebins = get_binfiles(linebeds, fastafile, shift, mode=opts.mode, merge=merge)

    margin = 0.12
    clen = Sizes(fastafile).mapping[chr]
    nbins = get_nbins(clen, shift)

    plt.rcParams["xtick.major.size"] = 0
    plt.rcParams["ytick.major.size"] = 0

    fig = plt.figure(1, (iopts.w, iopts.h))
    root = fig.add_axes([0, 0, 1, 1])

    root.text(0.5, 0.95, chr, ha="center", color="darkslategray")

    xstart, xend = margin, 1 - margin
    xlen = xend - xstart
    ratio = xlen / clen
    # Line plots
    ax = fig.add_axes([xstart, 0.6, xlen, 0.3])
    lineplot(ax, linebins, nbins, chr, window, shift)

    # Bar plots
    yy = 0.5
    yinterval = 0.08
    xs = lambda x: xstart + ratio * x
    r = 0.01
    fattend = 0.0025
    for bb in barbeds:
        root.text(xend + 0.01, yy, bb.split(".")[0], va="center")
        HorizontalChromosome(root, xstart, xend, yy, height=0.02)
        bb = Bed(bb)
        for b in bb:
            start, end = xs(b.start), xs(b.end)
            span = end - start
            if fatten and span < fattend:
                span = fattend

            root.add_patch(
                Rectangle((start, yy - r), span, 2 * r, lw=0, fc="darkslategray")
            )
        yy -= yinterval

    # Alternative bar plots
    offset = r / 2
    for bb in altbarbeds:
        root.text(xend + 0.01, yy, bb.split(".")[0], va="center")
        bb = Bed(bb)
        for i, b in enumerate(bb):
            start, end = xs(b.start), xs(b.end)
            span = end - start
            if span < 0.0001:
                continue
            offset = -offset
            root.add_patch(
                Rectangle(
                    (start, yy + offset), end - start, 0.003, lw=0, fc="darkslategray"
                )
            )
        yy -= yinterval

    root.set_xlim(0, 1)
    root.set_ylim(0, 1)
    root.set_axis_off()

    image_name = chr + "." + iopts.format
    savefig(image_name, dpi=iopts.dpi, iopts=iopts)

def multilineplot(args):
    """
    %prog multilineplot fastafile chr1

    Combine multiple line plots in one vertical stack
    Inputs must be BED-formatted.

    --lines: traditional line plots, useful for plotting feature freq
    """
    p = OptionParser(multilineplot.__doc__)
    p.add_option("--lines", help="Features to plot in lineplot")
    p.add_option("--colors", help="List of colors matching number of input bed files")
    p.add_option(
        "--mode",
        default="span",
        choices=("span", "count", "score"),
        help="Accumulate feature based on",
    )
    p.add_option(
        "--binned",
        default=False,
        action="store_true",
        help="Specify whether the input is already binned; "
        + "if True, input files are considered to be binfiles",
    )
    p.add_option("--ymax", type="int", help="Set Y-axis max")
    add_window_options(p)
    opts, args, iopts = p.set_image_options(args, figsize="8x5")

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

    fastafile, chr = args
    window, shift, subtract, merge = check_window_options(opts)
    linebeds = []
    colors = opts.colors
    if opts.lines:
        lines = opts.lines.split(",")
        assert len(colors) == len(lines), (
            "Number of chosen colors must match" + " number of input bed files"
        )
        linebeds = get_beds(lines, binned=opts.binned)

    linebins = get_binfiles(
        linebeds, fastafile, shift, mode=opts.mode, binned=opts.binned, merge=merge
    )

    clen = Sizes(fastafile).mapping[chr]
    nbins = get_nbins(clen, shift)

    plt.rcParams["xtick.major.size"] = 0
    plt.rcParams["ytick.major.size"] = 0
    plt.rcParams["figure.figsize"] = iopts.w, iopts.h

    fig, axarr = plt.subplots(nrows=len(lines))
    if len(linebeds) == 1:
        axarr = (axarr,)
    fig.suptitle(latex(chr), color="darkslategray")

    for i, ax in enumerate(axarr):
        lineplot(
            ax,
            [linebins[i]],
            nbins,
            chr,
            window,
            shift,
            color="{0}{1}".format(colors[i], "r"),
        )

    if opts.ymax:
        ax.set_ylim(0, opts.ymax)

    plt.subplots_adjust(hspace=0.5)

    image_name = chr + "." + iopts.format
    savefig(image_name, dpi=iopts.dpi, iopts=iopts)

def heatmap(args):
    """
    %prog heatmap fastafile chr1

    Combine stack plot with heatmap to show abundance of various tracks along
    given chromosome. Need to give multiple beds to --stacks and --heatmaps
    """
    p = OptionParser(heatmap.__doc__)
    p.add_option(
        "--stacks",
        default="Exons,Introns,DNA_transposons,Retrotransposons",
        help="Features to plot in stackplot",
    )
    p.add_option(
        "--heatmaps",
        default="Copia,Gypsy,hAT,Helitron,Introns,Exons",
        help="Features to plot in heatmaps",
    )
    p.add_option("--meres", default=None, help="Extra centromere / telomere features")
    add_window_options(p)
    opts, args, iopts = p.set_image_options(args, figsize="8x5")

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

    fastafile, chr = args
    window, shift, subtract, merge = check_window_options(opts)

    stacks = opts.stacks.split(",")
    heatmaps = opts.heatmaps.split(",")
    stackbeds = get_beds(stacks)
    heatmapbeds = get_beds(heatmaps)
    stackbins = get_binfiles(
        stackbeds, fastafile, shift, subtract=subtract, merge=merge
    )
    heatmapbins = get_binfiles(
        heatmapbeds, fastafile, shift, subtract=subtract, merge=merge
    )

    margin = 0.06
    inner = 0.015
    clen = Sizes(fastafile).mapping[chr]

    fig = plt.figure(1, (iopts.w, iopts.h))
    root = fig.add_axes([0, 0, 1, 1])

    # Gauge
    ratio = draw_gauge(root, margin, clen, rightmargin=4 * margin)
    yinterval = 0.3
    xx = margin
    yy = 1 - margin
    yy -= yinterval
    xlen = clen / ratio
    cc = chr
    if "_" in chr:
        ca, cb = chr.split("_")
        cc = ca[0].upper() + cb

    root.add_patch(Rectangle((xx, yy), xlen, yinterval - inner, color=gray))
    ax = fig.add_axes([xx, yy, xlen, yinterval - inner])

    nbins = get_nbins(clen, shift)

    owindow = clen / 100
    if owindow > window:
        window = owindow / shift * shift

    stackplot(ax, stackbins, nbins, palette, chr, window, shift)
    ax.text(
        0.1,
        0.9,
        cc,
        va="top",
        zorder=100,
        transform=ax.transAxes,
        bbox=dict(boxstyle="round", fc="w", alpha=0.5),
    )

    # Legends
    xx += xlen + 0.01
    yspace = (yinterval - inner) / (len(stackbins) + 1)
    yy = 1 - margin - yinterval
    for s, p in zip(stacks, palette):
        s = s.replace("_", " ")
        s = Registration.get(s, s)

        yy += yspace
        root.add_patch(Rectangle((xx, yy), inner, inner, color=p, lw=0))
        root.text(xx + 1.5 * inner, yy, s, size=10)

    yh = 0.05  # Heatmap height
    # Heatmaps
    xx = margin
    yy = 1 - margin - yinterval - inner
    for s, p in zip(heatmaps, heatmapbins):
        s = s.replace("_", " ")
        s = Registration.get(s, s)

        yy -= yh
        m = stackarray(p, chr, window, shift)

        Y = np.array([m, m])
        root.imshow(
            Y,
            extent=(xx, xx + xlen, yy, yy + yh - inner),
            interpolation="nearest",
            aspect="auto",
            cmap=iopts.cmap,
        )
        root.text(xx + xlen + 0.01, yy, s, size=10)

    yy -= yh

    meres = opts.meres
    if meres:
        bed = Bed(meres)
        for b in bed:
            if b.seqid != chr:
                continue
            pos = (b.start + b.end) / 2
            cpos = pos / ratio
            xx = margin + cpos
            accn = b.accn.capitalize()
            root.add_patch(CirclePolygon((xx, yy), radius=0.01, fc="m", ec="m"))
            root.text(xx + 0.014, yy, accn, va="center", color="m")

    root.set_xlim(0, 1)
    root.set_ylim(0, 1)
    root.set_axis_off()

    image_name = chr + "." + iopts.format
    savefig(image_name, dpi=iopts.dpi, iopts=iopts)

def draw_gauge(ax, margin, maxl, rightmargin=None):
    # Draw a gauge on the top of the canvas
    rightmargin = rightmargin or margin
    ax.plot([margin, 1 - rightmargin], [1 - margin, 1 - margin], "k-", lw=2)

    best_stride = autoscale(maxl)
    nintervals = maxl * 1.0 / best_stride

    xx, yy = margin, 1 - margin
    tip = 0.005
    xinterval = (1 - margin - rightmargin) / nintervals
    l = human_size(best_stride)
    if l[-1] == "b":
        suffix = target = l[-2:]

    for i in range(0, maxl + 1, best_stride):
        l = human_size(i, precision=0, target=target)
        if l[-1] == "b":
            l, suffix = l[:-2], l[-2:]
        ax.plot([xx, xx], [yy, yy + tip], "k-", lw=2)
        ax.text(xx, yy + 2 * tip, l, ha="center", size=13)
        xx += xinterval

    xx += 4 * tip - xinterval
    ax.text(xx + tip, yy + 2 * tip, suffix)

    return best_stride / xinterval

def get_binfiles(
    inputfiles, fastafile, shift, mode="span", subtract=None, binned=False, merge=True
):
    if not binned:
        binopts = ["--binsize={0}".format(shift)]
        binopts.append("--mode={0}".format(mode))
        if subtract:
            binopts.append("--subtract={0}".format(subtract))
        if not merge:
            binopts.append("--nomerge")
        binfiles = [bins([x, fastafile] + binopts) for x in inputfiles if op.exists(x)]
    else:
        binfiles = inputfiles
    binfiles = [BinFile(x) for x in binfiles]

    return binfiles

def stackarray(binfile, chr, window, shift):
    mn = binfile.mapping[chr]
    m, n = zip(*mn)

    m = np.array(m, dtype="float")
    n = np.array(n, dtype="float")

    w = window / shift
    m = moving_sum(m, window=w)
    n = moving_sum(n, window=w)
    m /= n

    return m

def stackplot(ax, binfiles, nbins, palette, chr, window, shift):
    t = np.arange(nbins, dtype="float") + 0.5
    m = np.zeros(nbins, dtype="float")
    zorders = range(10)[::-1]
    for binfile, p, z in zip(binfiles, palette, zorders):
        s = stackarray(binfile, chr, window, shift)
        m += s
        ax.fill_between(t, m, color=p, lw=0, zorder=z)

    ax.set_xlim(0, nbins)
    ax.set_ylim(0, 1)
    ax.set_axis_off()

def stack(args):
    """
    %prog stack fastafile

    Create landscape plots that show the amounts of genic sequences, and repetitive
    sequences along the chromosomes.
    """
    p = OptionParser(stack.__doc__)
    p.add_option("--top", default=10, type="int", help="Draw the first N chromosomes")
    p.add_option(
        "--stacks",
        default="Exons,Introns,DNA_transposons,Retrotransposons",
        help="Features to plot in stackplot",
    )
    p.add_option("--switch", help="Change chr names based on two-column file")
    add_window_options(p)
    opts, args, iopts = p.set_image_options(args, figsize="8x8")

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

    (fastafile,) = args
    top = opts.top
    window, shift, subtract, merge = check_window_options(opts)
    switch = opts.switch
    if switch:
        switch = DictFile(opts.switch)

    stacks = opts.stacks.split(",")
    bedfiles = get_beds(stacks)
    binfiles = get_binfiles(bedfiles, fastafile, shift, subtract=subtract, merge=merge)

    sizes = Sizes(fastafile)
    s = list(sizes.iter_sizes())[:top]
    maxl = max(x[1] for x in s)
    margin = 0.08
    inner = 0.02  # y distance between tracks

    pf = fastafile.rsplit(".", 1)[0]
    fig = plt.figure(1, (iopts.w, iopts.h))
    root = fig.add_axes([0, 0, 1, 1])

    # Gauge
    ratio = draw_gauge(root, margin, maxl)

    # Per chromosome
    yinterval = (1 - 2 * margin) / (top + 1)
    xx = margin
    yy = 1 - margin
    for chr, clen in s:
        yy -= yinterval
        xlen = clen / ratio
        cc = chr
        if "_" in chr:
            ca, cb = chr.split("_")
            cc = ca[0].upper() + cb

        if switch and cc in switch:
            cc = "\n".join((cc, "({0})".format(switch[cc])))

        root.add_patch(Rectangle((xx, yy), xlen, yinterval - inner, color=gray))
        ax = fig.add_axes([xx, yy, xlen, yinterval - inner])

        nbins = clen / shift
        if clen % shift:
            nbins += 1

        stackplot(ax, binfiles, nbins, palette, chr, window, shift)
        root.text(
            xx - 0.04, yy + 0.5 * (yinterval - inner), cc, ha="center", va="center"
        )

        ax.set_xlim(0, nbins)
        ax.set_ylim(0, 1)
        ax.set_axis_off()

    # Legends
    yy -= yinterval
    xx = margin
    for b, p in zip(bedfiles, palette):
        b = b.rsplit(".", 1)[0].replace("_", " ")
        b = Registration.get(b, b)

        root.add_patch(Rectangle((xx, yy), inner, inner, color=p, lw=0))
        xx += 2 * inner
        root.text(xx, yy, b, size=13)
        xx += len(b) * 0.012 + inner

    root.set_xlim(0, 1)
    root.set_ylim(0, 1)
    root.set_axis_off()

    image_name = pf + "." + iopts.format
    savefig(image_name, dpi=iopts.dpi, iopts=iopts)

if __name__ == "__main__":
    main()


text:
package edu.mayo.qdm.patient;

import org.apache.log4j.Logger;

import java.util.Date;

/**
 * @author Herman and Darin IHC
 */
public class Procedure extends Event {
    private static Logger logger = Logger.getLogger(Procedure.class);

    private ProcedureStatus procedureStatus;

    /*
     * For JSON only
     */
    private Procedure() {
        this(null, null);
    }

    public Procedure(Concept concept, ProcedureStatus procedureStatus) {
        this(concept, procedureStatus, null);
    }

    public Procedure(Concept concept, ProcedureStatus procedureStatus, Date startDate) {
        this(concept, procedureStatus, startDate, startDate);

    }

    public Procedure(Concept concept, ProcedureStatus procedureStatus, Date startDate, Date endDate) {
        super(concept, startDate, endDate);
        this.procedureStatus = procedureStatus;
    }

    public ProcedureStatus getProcedureStatus() {
        return procedureStatus;
    }

    public void setProcedureStatus(ProcedureStatus procedureStatus) {
        this.procedureStatus = procedureStatus;
    }

}

redpajama_set_name: RedPajamaGithub


text:
/* MACHINE GENERATED FILE, DO NOT EDIT */

#include <jni.h>
#include "extgl.h"

typedef void (APIENTRY *glMinSampleShadingARBPROC) (GLclampf value);

JNIEXPORT void JNICALL Java_org_lwjgl_opengl_ARBSampleShading_nglMinSampleShadingARB(JNIEnv *env, jclass clazz, jfloat value, jlong function_pointer) {
	glMinSampleShadingARBPROC glMinSampleShadingARB = (glMinSampleShadingARBPROC)((intptr_t)function_pointer);
	glMinSampleShadingARB(value);
}


text:
package org.trustedanalytics.scoring

import org.joda.time.DateTime
import org.trustedanalytics.scoring.ScoringServiceJsonProtocol.DataTypeJsonFormat
import org.trustedanalytics.scoring.interfaces.Model
import spray.json._

import scala.collection.mutable.ArrayBuffer

class DataOutputFormatJsonProtocol(model: Model) {

  implicit object DataInputFormat extends JsonFormat[Seq[Array[Any]]] {

    //don't need this method. just there to satisfy the API.
    override def write(obj: Seq[Array[Any]]): JsValue = ???

    override def read(json: JsValue): Seq[Array[Any]] = {
      val records = json.asJsObject.getFields("records") match {
        case Seq(JsArray(records)) => records
        case x => deserializationError(s"Expected array of records but got $x")
      }
      decodeRecords(records)
    }
  }

  implicit object DataOutputFormat extends JsonFormat[Array[Map[String, Any]]] {

    override def write(obj: Array[Map[String, Any]]): JsValue = {
      JsObject("data" -> new JsArray(obj.map(output => DataTypeJsonFormat.write(output)).toList))
    }

    //don't need this method. just there to satisfy the API.
    override def read(json: JsValue): Array[Map[String, Any]] = ???
  }

  def decodeRecords(records: List[JsValue]): Seq[Array[Any]] = {
    val decodedRecords: Seq[Map[String, Any]] = records.map { record =>
      record match {
        case JsObject(fields) =>
          val decodedRecord: Map[String, Any] = for ((feature, value) <- fields) yield (feature, decodeJValue(value))
          decodedRecord
      }
    }
    var features: Seq[Array[Any]] = Seq[Array[Any]]()
    decodedRecords.foreach(decodedRecord => {
      val featureArray = new Array[Any](decodedRecord.size)
      var counter = 0
      decodedRecord.foreach({
        case (name, value) => {
          featureArray(counter) = value
          counter = counter + 1
        }
      })
      features = features :+ featureArray
    })
    features
  }

  def decodeJValue(v: JsValue): Any = {
    v match {
      case JsString(s) => s
      case JsNumber(n) => n.toDouble
      case JsArray(items) => for (item <- items) yield decodeJValue(item)
      case JsNull => null
      case JsObject(fields) =>
        val decodedValue: Map[String, Any] = for ((feature, value) <- fields) yield (feature, decodeJValue(value))
        decodedValue
      case x => deserializationError(s"Unexpected JSON type in record $x")
    }
  }

}


text:
import { JsonValue } from '@angular-devkit/core';
import { join } from 'path';
import { v4 as uuidV4 } from 'uuid';
import { Argv } from 'yargs';
import {
  CommandModule,
  CommandModuleError,
  CommandModuleImplementation,
  Options,
} from '../../command-builder/command-module';
import { getWorkspaceRaw, validateWorkspace } from '../../utilities/config';
import { JSONFile, parseJson } from '../../utilities/json-file';

interface ConfigCommandArgs {
  'json-path'?: string;
  value?: string;
  global?: boolean;
}

export class ConfigCommandModule
  extends CommandModule<ConfigCommandArgs>
  implements CommandModuleImplementation<ConfigCommandArgs>
{
  command = 'config [json-path] [value]';
  describe =
    'Retrieves or sets Angular configuration values in the angular.json file for the workspace.';
  longDescriptionPath = join(__dirname, 'long-description.md');

  builder(localYargs: Argv): Argv<ConfigCommandArgs> {
    return localYargs
      .positional('json-path', {
        description:
          `The configuration key to set or query, in JSON path format. ` +
          `For example: "a[3].foo.bar[2]". If no new value is provided, returns the current value of this key.`,
        type: 'string',
      })
      .positional('value', {
        description: 'If provided, a new value for the given configuration key.',
        type: 'string',
      })
      .option('global', {
        description: `Access the global configuration in the caller's home directory.`,
        alias: ['g'],
        type: 'boolean',
        default: false,
      })
      .strict();
  }

  async run(options: Options<ConfigCommandArgs>): Promise<number | void> {
    const level = options.global ? 'global' : 'local';
    const [config] = getWorkspaceRaw(level);

    if (options.value == undefined) {
      if (!config) {
        this.context.logger.error('No config found.');

        return 1;
      }

      return this.get(config, options);
    } else {
      return this.set(options);
    }
  }

  private get(jsonFile: JSONFile, options: Options<ConfigCommandArgs>): number {
    const { logger } = this.context;

    const value = options.jsonPath
      ? jsonFile.get(parseJsonPath(options.jsonPath))
      : jsonFile.content;

    if (value === undefined) {
      logger.error('Value cannot be found.');

      return 1;
    } else if (typeof value === 'string') {
      logger.info(value);
    } else {
      logger.info(JSON.stringify(value, null, 2));
    }

    return 0;
  }

  private async set(options: Options<ConfigCommandArgs>): Promise<number | void> {
    if (!options.jsonPath?.trim()) {
      throw new CommandModuleError('Invalid Path.');
    }

    const validGlobalCliPaths = new Set<string>([
      'cli.warnings.versionMismatch',
      'cli.defaultCollection',
      'cli.schematicCollections',
      'cli.packageManager',

      'cli.analytics',
      'cli.analyticsSharing.tracking',
      'cli.analyticsSharing.uuid',

      'cli.completion.prompted',
    ]);

    if (
      options.global &&
      !options.jsonPath.startsWith('schematics.') &&
      !validGlobalCliPaths.has(options.jsonPath)
    ) {
      throw new CommandModuleError('Invalid Path.');
    }

    const [config, configPath] = getWorkspaceRaw(options.global ? 'global' : 'local');
    const { logger } = this.context;

    if (!config || !configPath) {
      throw new CommandModuleError('Confguration file cannot be found.');
    }

    const normalizeUUIDValue = (v: string | undefined) => (v === '' ? uuidV4() : `${v}`);

    const value =
      options.jsonPath === 'cli.analyticsSharing.uuid'
        ? normalizeUUIDValue(options.value)
        : options.value;

    const modified = config.modify(parseJsonPath(options.jsonPath), normalizeValue(value));

    if (!modified) {
      logger.error('Value cannot be found.');

      return 1;
    }

    await validateWorkspace(parseJson(config.content));

    config.save();

    return 0;
  }
}

/**
 * Splits a JSON path string into fragments. Fragments can be used to get the value referenced
 * by the path. For example, a path of "a[3].foo.bar[2]" would give you a fragment array of
 * ["a", 3, "foo", "bar", 2].
 * @param path The JSON string to parse.
 * @returns {(string|number)[]} The fragments for the string.
 * @private
 */
function parseJsonPath(path: string): (string | number)[] {
  const fragments = (path || '').split(/\./g);
  const result: (string | number)[] = [];

  while (fragments.length > 0) {
    const fragment = fragments.shift();
    if (fragment == undefined) {
      break;
    }

    const match = fragment.match(/([^[]+)((\[.*\])*)/);
    if (!match) {
      throw new CommandModuleError('Invalid JSON path.');
    }

    result.push(match[1]);
    if (match[2]) {
      const indices = match[2]
        .slice(1, -1)
        .split('][')
        .map((x) => (/^\d$/.test(x) ? +x : x.replace(/"|'/g, '')));
      result.push(...indices);
    }
  }

  return result.filter((fragment) => fragment != null);
}

function normalizeValue(value: string | undefined | boolean | number): JsonValue | undefined {
  const valueString = `${value}`.trim();
  switch (valueString) {
    case 'true':
      return true;
    case 'false':
      return false;
    case 'null':
      return null;
    case 'undefined':
      return undefined;
  }

  if (isFinite(+valueString)) {
    return +valueString;
  }

  try {
    // We use `JSON.parse` instead of `parseJson` because the latter will parse UUIDs
    // and convert them into a numberic entities.
    // Example: 73b61974-182c-48e4-b4c6-30ddf08c5c98 -> 73.
    // These values should never contain comments, therefore using `JSON.parse` is safe.
    return JSON.parse(valueString);
  } catch {
    return value;
  }
}


text:
using UsingCustomMVVM.Models;
using UsingCustomMVVM.ViewModels;

using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

namespace UsingCustomMVVM.Views
{
    public sealed partial class MasterDetailDetailPage : Page
    {
        public MasterDetailDetailViewModel ViewModel { get; } = new MasterDetailDetailViewModel();
        public MasterDetailDetailPage()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            ViewModel.Item = e.Parameter as SampleModel;
        }
    }
}


text:
// inect-router.js

var fs = require('fs');

var inject_router_json_path = './inject-router.json'

function makeFile(path,string=""){
    fs.access(path,function(err){
        if(err){
            fs.writeFileSync(path,string);
        }
    });
}

exports.inject = function(url,html,callback){
    //inject code
    fs.readFile(inject_router_json_path, 'utf-8', function(err, json){
        if (err){
            throw err;
        }else{
            if (json.length>1){
                var routers = JSON.parse(json);
            }else{
                var routers = {}; //build routers for first use
            }
            for (var i in routers){
                var router = routers[i];
                var pattern = router.pattern;
                if(url.match(pattern)){ //match url
                    var path_css = router.path_css;
                    var path_js = router.path_js;
                    var code_css = fs.readFileSync(path_css);
                    code_css = '';
                    var code_js = fs.readFileSync(path_js);
                    code_js = '';
                    html = html.replace('',code_css+''); //inject css code
                    html = html.replace('',code_js+''); //inject js code
                }
            }
            callback(html); //callback
        }
    });
}

exports.addRouter = function(pattern){
    var inRouters = function(pattern,routers){
        for (var i in routers){
            var router = routers[i];
            var pattern_in = router.pattern;
            if (pattern_in==pattern){
                return i;
            }
        }
        return (-1);
    }
    fs.readFile(inject_router_json_path, 'utf-8', function(err, json){
        if (err){
            throw err;
        }else{
            if (json.length>2){ //not null
                var routers = JSON.parse(json);
            }else{ //null
                var routers = []; //build routers for first use
            }
            var index = inRouters(pattern,routers);
            if (index>-1){ //already in
                var id = routers[index].id;
                console.log('Router already in: // pattern: '+pattern+' // pid: '+id);
            }else{ //not in
                var router = {};
                var id = routers.length;
                var path_css = './code/css/'+id+'.css';
                var path_js = './code/js/'+id+'.js';
                makeFile(path_css,"/*"+pattern+"*/");
                makeFile(path_js,"/*"+pattern+"*/");
                router.pattern = pattern;
                router.id = id;
                router.path_css = path_css;
                router.path_js = path_js;
                console.log(router);
                routers.push(router);
                json = JSON.stringify(routers)
                console.log(json);
                fs.writeFile(inject_router_json_path, json, 'utf-8', function(err){
                    if (err){
                        throw err;
                    }else{
                        console.log('Add router '+pattern+' : '+id+' success');
                    }
                });
            }
        }
    });
}

/*exports.addRouter('.+guaihaha.com.+');
exports.addRouter('.+m.23wx.com.+');*/

/*exports.addRouter = function(pattern,code){
    var inRouters = function(pattern,routers){
        for (var i in routers){
            var router = routers[i];
            var pattern_in = router.pattern;
            if (pattern_in==pattern){
                return i;
            }
        }
        return (-1);
    }
    fs.readFile(inject_router_json_path, 'utf-8', function(err, json){
        if (err){
            throw err;
        }else{
            if (json.length>2){
                var routers = JSON.parse(json);
            }else{
                var routers = []; //build routers for first use
            }
            var index = inRouters(pattern,routers);
            if (index>-1){ //already in
                console.log('router already in');
                routers[index].code = code;
                json = JSON.stringify(routers)
                console.log(json);
                fs.writeFile(inject_router_json_path, json, 'utf-8', function(err){
                    if (err){
                        throw err;
                    }else{
                        console.log('Change router '+pattern+' success');
                    }
                });
            }else{
                var router = {};
                router.pattern = pattern;
                router.code = code;
                console.log(router);
                routers.push(router);
                json = JSON.stringify(routers)
                console.log(json);
                fs.writeFile(inject_router_json_path, json, 'utf-8', function(err){
                    if (err){
                        throw err;
                    }else{
                        console.log('Add router '+pattern+' success');
                    }
                });
            }
        }
    });
}*/


text:
using namespace std;

int main(int argc, char** argv){

	#pragma omp parallel
	#pragma omp critical
	{
		cout << "Hi, I'm thread " << omp_get_thread_num() << " of " << omp_get_num_threads() << endl;
	}

	return 0;
}


text:
name: Bug report
about: Create a report to help us improve
title: "[BUG]"
labels: 'Type: bug'
assignees: steven-murray

---

**Describe the bug**
A clear and concise description of what the bug is.

**To Reproduce**
Steps to reproduce the behavior:
1.
2.

**Expected behavior**
A clear and concise description of what you expected to happen.

 - OS: [e.g. Ubuntu]
 - Version [e.g. 3.1.0]

**Additional context**
Add any other context about the problem here.


text:
try:
    from urlparse import urljoin
except ImportError:
    from urllib.parse import urljoin

from django.conf import settings
from django.core.urlresolvers import reverse

from rest_framework import serializers

from apps.api.models import Rank, GeekPlayers, Geek, GeekStats

class RankSerializer(serializers.ModelSerializer):
    class Meta(object):
        model = Rank
        fields = ('name', 'rank')

class GeekPlayersSerializer(serializers.ModelSerializer):
    class Meta(object):
        model = GeekPlayers
        fields = ('best', 'recommended', 'not_recommended',)

class GeekListSerializer(serializers.HyperlinkedModelSerializer):
    best_number_of_players = serializers.SerializerMethodField()

    def get_best_number_of_players(self, obj):
        return obj.best_number_of_players

    class Meta(object):
        model = Geek
        fields = ('ranking', 'best_number_of_players', 'suggested_age', 'language_dependence',
                  'object_id', 'url')

class GeekSerializer(serializers.HyperlinkedModelSerializer):
    suggested_players = GeekPlayersSerializer(many=True)
    stats = serializers.SerializerMethodField()
    hotness = serializers.SerializerMethodField()
    best_number_of_players = serializers.SerializerMethodField()

    def get_stats(self, obj):
        return urljoin(settings.BASE_API, reverse('api-v1:game:geekstats-detail',
                                                  args=[obj.game.id]))

    def get_hotness(self, obj):
        return urljoin(settings.BASE_API, reverse('api-v1:game:hotness-detail',
                                                  args=[obj.game.id]))

    def get_best_number_of_players(self, obj):
        return obj.best_number_of_players

    class Meta(object):
        model = Geek
        fields = ('ranking', 'best_number_of_players', 'suggested_players',
                  'suggested_age', 'language_dependence', 'object_id', 'url', 'last_scraped',
                  'stats', 'hotness')

class GeekStatsSerializer(serializers.ModelSerializer):
    game = serializers.SerializerMethodField()
    ranks = RankSerializer(many=True)

    def get_game(self, obj):
        return urljoin(settings.BASE_API, reverse('api-v1:game:game-detail',
                                                  args=[obj.geek.game.id]))

    class Meta(object):
        model = GeekStats
        fields = ('ranks', 'average_rating', 'num_ratings', 'fans', 'total_plays',
                  'users_owning', 'users_trading', 'users_wanting', 'date_added', 'game')


text:
package com.toopher;

import java.io.IOException;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;

/**
 * Request errors from API calls
 *
 */
public class RequestError extends Exception {

    public RequestError(ClientProtocolException e) {
        super("Http protocol error", e);
    }

    public RequestError(IOException e) {
        super("Connection error", e);
    }

    public RequestError(JSONException e) {
        super("Unexpected response format", e);
    }

    public RequestError(Exception e) {
        super("Request error", e);
    }

    private static final long serialVersionUID = -1479647692976296897L;
}


text:
package com.gs.obevo.dbmetadata.api;

/**
 * Corresponds to the package object type in Oracle.
 */
public interface DaPackage extends DaDatabaseObject {
}


text:
import os
import sys
import yaml
import subprocess

MELLANOX_TOOLS = ''

MELLANOX_DEBUG_ENV_VAR = 'MLNX_DEBUG'

MELLANOX_TOOLS_LOCATION = [
  '/usr/bin/mellanox-config-tools',
  '/opt/mellanox/bin/mellanox-config-tools',
]

for location in MELLANOX_TOOLS_LOCATION:
  if os.path.exists(location):
    MELLANOX_TOOLS = location
    break

def config_tools_call(option):
  if MELLANOX_TOOLS == '':
    print >> sys.stderr, 'Error requirements: not found Mellanox configuration tools'
    return 1
  call_command = ['/bin/bash', MELLANOX_TOOLS] + option
  rc = (subprocess.call(call_command) == 0)
  if not rc:
    print >> sys.stderr, 'Error call: ' + ' '.join(call_command)
  return rc

def configure_repository_ofed(version=''):
  return config_tools_call(['configure-repository-ofed', str(version)])

def configure_repository_openstack(version='kilo'):
  return config_tools_call(['configure-repository-openstack', str(version)])

def ofed_install(version=''):
  return config_tools_call(['ofed', 'install', str(version)])

def ofed_bundle_deploy(version=''):
  return config_tools_call(['ofed-bundle-deploy', str(version)])

def ofed_remove():
  return config_tools_call(['ofed', 'remove'])

def e_ipoib_enable():
  return config_tools_call(['e-ipoib', 'enable'])

def e_ipoib_disable():
  return config_tools_call(['e-ipoib', 'disable'])

def openibd_enable():
  return config_tools_call(['openibd', 'enable'])

def openibd_disable():
  return config_tools_call(['openibd', 'disable'])

def openibd_stop():
  return config_tools_call(['openibd', 'stop'])

def openibd_start():
  return config_tools_call(['openibd', 'start'])

def openibd_restart():
  return config_tools_call(['openibd', 'restart'])

def mst_enable():
  return config_tools_call(['mst', 'enable'])

def mst_disable():
  return config_tools_call(['mst', 'disable'])

def mst_stop():
  return config_tools_call(['mst', 'stop'])

def mst_start():
  return config_tools_call(['mst', 'start'])

def mst_restart():
  return config_tools_call(['mst', 'restart'])

def pk_to_vlan_map(vlan_min=1, vlan_max=16, pk_min=1):
  return config_tools_call(['pk-to-vlan-map', str(vlan_min), str(vlan_max), str(pk_min)])

def opensmd_enable():
  return config_tools_call(['opensmd', 'enable'])

def opensmd_disable():
  return config_tools_call(['opensmd', 'disable'])

def opensmd_stop():
  return config_tools_call(['opensmd', 'stop'])

def opensmd_start():
  return config_tools_call(['opensmd', 'start'])

def opensmd_restart():
  return config_tools_call(['opensmd', 'restart'])

def connectx_port_config(mode_port_0='ib', mode_port_1='ib'):
  return config_tools_call(['connectx-port-config', str(mode_port_0), str(mode_port_1)])

def sriov_enable():
  return config_tools_call(['sriov', 'enable'])

def sriov_disable():
  return config_tools_call(['sriov', 'disable'])

def sriov_fw_enable():
  return config_tools_call(['sriov-fw', 'enable'])

def sriov_fw_disable():
  return config_tools_call(['sriov-fw', 'disable'])

def sysctl_conf_set(var, val):
  return config_tools_call(['sysctl-conf', 'set', str(var), str(val)])

def sysctl_conf_unset(var):
  return config_tools_call(['sysctl-conf', 'unset', str(var)])

def interface_set(if_name, if_alias, ip_address, net_mask='255.255.255.0'):
  return config_tools_call(['interface', 'set', str(if_name), str(if_alias), str(ip_address), str(net_mask)])

def interface_unset(if_name, if_alias):
  return config_tools_call(['interface', 'unset', str(if_name), str(if_alias)])

def interface_up(if_name, if_alias):
  return config_tools_call(['interface', 'up', str(if_name), str(if_alias)])

def interface_down(if_name, if_alias):
  return config_tools_call(['interface', 'down', str(if_name), str(if_alias)])

def set_vf_type_num(mode_port_0='ib', mode_port_1='ib', num_vf=0, probe_vf=0):
  return config_tools_call(['set-vf-type-num', str(mode_port_0), str(mode_port_1), str(num_vf), str(probe_vf)])

def burn_vfs_in_fw(num_vf=16):
  return config_tools_call(['burn-vfs-in-fw', str(num_vf)])

def udev_namer_enable():
  return config_tools_call(['udev-namer', 'enable'])

def udev_namer_disable():
  return config_tools_call(['udev-namer', 'disable'])

def udev_namer_config_set(var, val):
  return config_tools_call(['udev-namer-config', 'set', str(var), str(val)])

def udev_namer_config_unset(var):
  return config_tools_call(['udev-namer-config', 'unset', str(var)])

class ConfigToolsService():

  def __init__(self, srv):
    self.srv = srv

  def _call_ (self, cmd):
    if self.srv == 'opensmd' or self.srv == 'openibd' or self.srv == 'mst':
      return config_tools_call([self.srv, cmd])
    else:
      return False

  def enable (self):
    return self._call_('enable')

  def disable (self):
    return self._call_('disable')

  def start (self):
    return self._call_('start')

  def stop (self):
    return self._call_('stop')

  def restart (self):
    return self._call_('restart')

class ConfigToolsOpensmdService(ConfigToolsService):

  def vlan2pk (self, vlan_min=1, vlan_max=16, pk_min=1):
    return pk_to_vlan_map(vlan_min, vlan_max, pk_min)

class ConfigToolsRepository():

  def ofed (self, version=''):
    return configure_repository_ofed(version)

  def openstack (self, version='kilo'):
    return configure_repository_openstack(version)

class ConfigToolsOfed():

  def install (self, version=''):
    return ofed_install(version)

  def bundle_deploy (self, version=''):
    return ofed_bundle_deploy(version)

  def remove (self):
    return ofed_remove()

class ConfigToolsEIPOIB():

  def enable (self):
    return e_ipoib_enable()

  def disable (self):
    return e_ipoib_disable()

class ConfigToolsSysctl():

  def set (self, var, val):
    return sysctl_conf_set(var, val)

  def unset (self, var):
    return sysctl_conf_unset(var)

class ConfigToolsInterface():

  def set (self, if_name, if_alias, ip_address, net_mask='255.255.255.0'):
    return interface_set(if_name, if_alias, ip_address, net_mask)

  def unset (self, if_name, if_alias):
    return interface_unset(if_name, if_alias)

  def up (self, if_name, if_alias):
    return interface_up(if_name, if_alias)

  def down (self, if_name, if_alias):
    return interface_down(if_name, if_alias)

class ConfigToolsSRIOVKernel():

  def enable (self):
    return sriov_enable()

  def disable (self):
    return sriov_disable()

class ConfigToolsSRIOVFirmware():

  def enable (self):
    return sriov_fw_enable()

  def disable (self):
    return sriov_fw_disable()

  def burn (self, num_vf=16):
    return burn_vfs_in_fw(num_vf)

class ConfigToolsSRIOVModprobe():

  def set (self, mode_port_0='ib', mode_port_1='ib', num_vf=0, probe_vf=0):
    return set_vf_type_num(mode_port_0, mode_port_1, num_vf, probe_vf)

class ConfigToolsSRIOV():

  def __init__(self):
    self.kernel     = ConfigToolsSRIOVKernel()
    self.firmware   = ConfigToolsSRIOVFirmware()
    self.modprobe   = ConfigToolsSRIOVModprobe()

class ConfigToolsConnectx():

  def set (self, mode_port_0='ib', mode_port_1='ib'):
    return connectx_port_config(mode_port_0, mode_port_1)

class ConfigToolsUDEVNamer():

  def enable (self):
    return udev_namer_enable()

  def disable (self):
    return udev_namer_disable()

  def set (self, var, val):
    return udev_namer_config_set(var, val)

  def unset (self, var):
    return udev_namer_config_unset(var)

class ConfigTools(object):

  def __init__(self):

    self._debug     = False
    try:
      dm = os.environ[MELLANOX_DEBUG_ENV_VAR]
    except:
      dm = 'no'
      os.environ[MELLANOX_DEBUG_ENV_VAR] = dm
    if dm == 'yes':
      self._debug   = True

    self.repository = ConfigToolsRepository()
    self.ofed       = ConfigToolsOfed()
    self.eipoib     = ConfigToolsEIPOIB()
    self.openibd    = ConfigToolsService('openibd')
    self.mst        = ConfigToolsService('mst')
    self.opensmd    = ConfigToolsOpensmdService('opensmd')
    self.sysctl     = ConfigToolsSysctl()
    self.interface  = ConfigToolsInterface()
    self.sriov      = ConfigToolsSRIOV()
    self.connectx   = ConfigToolsConnectx()
    self.udevnamer  = ConfigToolsUDEVNamer()

  @property
  def debug(self):
    return self._debug

  @debug.setter
  def debug(self, v):
    self._debug = v
    allow_debug = "no"
    if self._debug:
      allow_debug = "yes"
    os.environ[MELLANOX_DEBUG_ENV_VAR] = allow_debug


text:
import micawber
from docutils import nodes
from docutils.parsers.rst import Directive, directives

class Media(Directive):
    """
    Restructured text extension for inserting any sort of media using micawber

    see: http://ralsina.me/weblog/posts/the-best-restructuredtext-directive-ever-really.html
    """
    has_content = False
    required_arguments = 1

    def run(self):
        providers = micawber.bootstrap_basic()
        return [nodes.raw('', micawber.parse_text(self.arguments[0], providers), format='html')]

directives.register_directive('media', Media)


text:
goog.provide('shaka.offline.OfflineScheme');

goog.require('shaka.net.NetworkingEngine');
goog.require('shaka.offline.OfflineUri');
goog.require('shaka.offline.StorageEngineFactory');
goog.require('shaka.util.AbortableOperation');
goog.require('shaka.util.Error');

/**
 * @namespace
 * @summary A plugin that handles requests for offline content.
 * @param {string} uri
 * @param {shakaExtern.Request} request
 * @return {!shakaExtern.IAbortableOperation.<shakaExtern.Response>}
 * @export
 */
shaka.offline.OfflineScheme = function(uri, request) {
  var manifestId = shaka.offline.OfflineUri.uriToManifestId(uri);
  if (manifestId != null) {
    return shaka.offline.OfflineScheme.onManifest_(uri);
  }

  var segmentId = shaka.offline.OfflineUri.uriToSegmentId(uri);
  if (segmentId != null) {
    return shaka.offline.OfflineScheme.onSegment_(segmentId, uri);
  }

  return shaka.util.AbortableOperation.failed(
      new shaka.util.Error(
          shaka.util.Error.Severity.CRITICAL,
          shaka.util.Error.Category.NETWORK,
          shaka.util.Error.Code.MALFORMED_OFFLINE_URI,
          uri));
};

/**
 * @param {string} uri
 * @return {!shakaExtern.IAbortableOperation.<shakaExtern.Response>}
 * @private
 */
shaka.offline.OfflineScheme.onManifest_ = function(uri) {
  /** @type {shakaExtern.Response} */
  var response = {
    uri: uri,
    data: new ArrayBuffer(0),
    headers: {'content-type': 'application/x-offline-manifest'}
  };

  return shaka.util.AbortableOperation.completed(response);
};

/**
 * @param {number} id
 * @param {string} uri
 * @return {!shakaExtern.IAbortableOperation.<shakaExtern.Response>}
 * @private
 */
shaka.offline.OfflineScheme.onSegment_ = function(id, uri) {
  /** @type {shaka.offline.IStorageEngine} */
  var storageEngine;
  var segment;

  var promise = shaka.offline.StorageEngineFactory.createStorageEngine()
      .then(function(se) {
        storageEngine = se;
        return storageEngine.getSegment(id);
      })
      .then(function(seg) {
        segment = seg;
        return storageEngine.destroy();
      })
      .then(function() {
        if (!segment) {
          throw new shaka.util.Error(
              shaka.util.Error.Severity.CRITICAL,
              shaka.util.Error.Category.STORAGE,
              shaka.util.Error.Code.REQUESTED_ITEM_NOT_FOUND,
              id);
        }

        /** @type {shakaExtern.Response} */
        var response = {
          uri: uri,
          data: segment.data,
          headers: {}
        };

        return response;
      });

  // TODO: support abort() in OfflineScheme
  return shaka.util.AbortableOperation.notAbortable(promise);
};

shaka.net.NetworkingEngine.registerScheme(
    'offline', shaka.offline.OfflineScheme);


text:
require 'spec_helper'

describe Users do
    context 'validations' do
        it { should validate_uniqueness_of(:email) }
    end
end


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>DragDrop Widget Test 2</title>
  <link rel="stylesheet" type="text/css" href="../../../src/widgets/themes/default/kekule.css" />

Panel 1

Panel 2


text:
namespace net {

namespace {

const size_t kKeySize = 16;
const size_t kNoncePrefixSize = 4;

}  // namespace

Aes128Gcm12Encrypter::Aes128Gcm12Encrypter()
    : AeadBaseEncrypter(EVP_aead_aes_128_gcm(),
                        kKeySize,
                        kAuthTagSize,
                        kNoncePrefixSize) {
  static_assert(kKeySize <= kMaxKeySize, "key size too big");
  static_assert(kNoncePrefixSize <= kMaxNoncePrefixSize,
                "nonce prefix size too big");
}

Aes128Gcm12Encrypter::~Aes128Gcm12Encrypter() {}

}  // namespace net


text:
mex -largeArrayDims spmtimesd.c
mex -largeArrayDims mex_compute_mscores_K_chi2.c
mex -largeArrayDims mexLap.c
mex -largeArrayDims mex_lap_munkres.cpp munkres.cpp


text:
package org.wildfly.camel.test.cdi.subC;

import javax.enterprise.context.ApplicationScoped;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.camel.cdi.CdiRouteBuilder;
import org.apache.camel.cdi.ContextName;

@ApplicationScoped
@ContextName("cdi-tx-context")
public class JTAErrorHandlerRouteBuilder extends CdiRouteBuilder {

    @PersistenceContext
    private EntityManager entityManager;

    private boolean forceRollback = true;

    @Override
    public void configure() throws Exception {

        errorHandler(transactionErrorHandler()
            .setTransactionPolicy("PROPAGATION_REQUIRED")
            .maximumRedeliveries(1)
            .onRedelivery(exchange -> {
                Order order = exchange.getIn().getBody(Order.class);
                order.setProductName(order.getProductName() + " redelivered");
        }));

        from("direct:start")
        .transacted("PROPAGATION_REQUIRED")
        .process(exchange -> {
            Order order = exchange.getIn().getBody(Order.class);
            entityManager.merge(order);

            if (forceRollback) {
                forceRollback = false;
                throw new IllegalStateException("Forced exception");
            }
        })
        .to("mock:result");
    }
}


text:
package concurrent

import (
	"sync"
	"sync/atomic"
)

// LazyLoader allows a function to be lazily atomically loaded.
type LazyLoader interface {
	Load() (interface{}, error)
}

// NewLazyLoader creates a new LazyLoader.
func NewLazyLoader(f func() (interface{}, error)) LazyLoader {
	return newLazyLoader(f)
}

type lazyLoader struct {
	once  *sync.Once
	f     func() (interface{}, error)
	value *atomic.Value
	err   *atomic.Value
}

func newLazyLoader(f func() (interface{}, error)) *lazyLoader {
	return &lazyLoader{&sync.Once{}, f, &atomic.Value{}, &atomic.Value{}}
}

func (l *lazyLoader) Load() (interface{}, error) {
	l.once.Do(func() {
		value, err := l.f()
		if value != nil {
			l.value.Store(value)
		}
		if err != nil {
			l.err.Store(err)
		}
	})
	value := l.value.Load()
	err := l.err.Load()
	if err != nil {
		return value, err.(error)
	}
	return value, nil
}


text:
import React from 'react'
import './Header.scss'
import { Row, Col, ButtonToolbar, Button } from 'react-bootstrap'

export const Header = () => (

    <Row>

Impot cible img

      <Col md={4} mdOffset={8}>
        <ButtonToolbar>
          <Button >Comment ca marche</Button>
          <Button bsStyle='primary'>Espace client</Button>
        </ButtonToolbar>
      </Col>
    </Row>

)

export default Header


text:
local dialog            = require("cp.dialog")
local fcp               = require("cp.apple.finalcutpro")
local tools             = require("cp.tools")

--------------------------------------------------------------------------------
--
-- CONSTANTS:
--
--------------------------------------------------------------------------------

-- PRIORITY
-- Constant
-- The menubar position priority.
local PRIORITY = 20

-- PLIST_PATH
-- Constant
-- Property List Path
local PLIST_PATH = "/Contents/Frameworks/Flexo.framework/Versions/A/Resources/en.lproj/FFLocalizable.strings"

--------------------------------------------------------------------------------
--
-- THE MODULE:
--
--------------------------------------------------------------------------------
local mod = {}

--- plugins.finalcutpro.hacks.smartcollectionslabel.change() -> none
--- Function
--- Triggers the Change Smart Collections Label Dialog Boxes.
---
--- Parameters:
---  * None
---
--- Returns:
---  * `true` if successful otherwise `false`.
function mod.change()

    --------------------------------------------------------------------------------
    -- Get existing value:
    --------------------------------------------------------------------------------
    local FFOrganizerSmartCollections = ""
    local executeResult = hs.execute("/usr/libexec/PlistBuddy -c \"Print :FFOrganizerSmartCollections\" '" .. fcp:getPath() .. PLIST_PATH .. "'")
    if tools.trim(executeResult) ~= "" then FFOrganizerSmartCollections = executeResult end

    --------------------------------------------------------------------------------
    -- If Final Cut Pro is running...
    --------------------------------------------------------------------------------
    local restartStatus = false
    if fcp:isRunning() then
        if dialog.displayYesNoQuestion(i18n("change"), i18n("doYouWantToContinue")) then
            restartStatus = true
        else
            return true
        end
    end

    --------------------------------------------------------------------------------
    -- Ask user what to set the backup interval to:
    --------------------------------------------------------------------------------
    local userSelectedSmartCollectionsLabel = dialog.displayTextBoxMessage(i18n("smartCollectionsLabelTextbox"), i18n("smartCollectionsLabelError"), tools.trim(FFOrganizerSmartCollections))
    if not userSelectedSmartCollectionsLabel then
        return false
    end

    --------------------------------------------------------------------------------
    -- Update plist for every Flexo language:
    --------------------------------------------------------------------------------
    local executeCommands = {}
    for k, _ in pairs(fcp:getFlexoLanguages()) do
        local executeCommand = "/usr/libexec/PlistBuddy -c \"Set :FFOrganizerSmartCollections " .. tools.trim(userSelectedSmartCollectionsLabel) .. "\" '" .. fcp:getPath() .. "/Contents/Frameworks/Flexo.framework/Versions/A/Resources/" .. fcp:getFlexoLanguages()[k] .. ".lproj/FFLocalizable.strings'"
        executeCommands[#executeCommands + 1] = executeCommand
    end
    local result = tools.executeWithAdministratorPrivileges(executeCommands)
    if type(result) == "string" then
        dialog.displayErrorMessage(result)
    end

    --------------------------------------------------------------------------------
    -- Restart Final Cut Pro:
    --------------------------------------------------------------------------------
    if restartStatus then
        if not fcp:restart() then
            --------------------------------------------------------------------------------
            -- Failed to restart Final Cut Pro:
            --------------------------------------------------------------------------------
            dialog.displayErrorMessage(i18n("failedToRestart"))
            return false
        end
    end

end

--------------------------------------------------------------------------------
--
-- THE PLUGIN:
--
--------------------------------------------------------------------------------
local plugin = {
    id              = "finalcutpro.hacks.smartcollectionslabel",
    group           = "finalcutpro",
    dependencies    = {
        ["finalcutpro.menu.administrator.advancedfeatures"] = "advancedfeatures",
        ["finalcutpro.commands"]                            = "fcpxCmds",
    }
}

--------------------------------------------------------------------------------
-- INITIALISE PLUGIN:
--------------------------------------------------------------------------------
function plugin.init(deps)

    --------------------------------------------------------------------------------
    -- Setup Menu:
    --------------------------------------------------------------------------------
    deps.advancedfeatures
        :addItem(PRIORITY, function()
            return { title = i18n("changeSmartCollectionLabel"),    fn = mod.change }
        end)

    --------------------------------------------------------------------------------
    -- Setup Command:
    --------------------------------------------------------------------------------
    deps.fcpxCmds
        :add("cpChangeSmartCollectionsLabel")
        :whenActivated(mod.change)

    --------------------------------------------------------------------------------
    -- Return Module:
    --------------------------------------------------------------------------------
    return mod

end

return plugin


text:
package system

import com.ibm.spark.kernel.protocol.v5.client.SparkKernelClient
import org.scalatest.concurrent.Eventually
import org.scalatest.time.{Seconds, Milliseconds, Span}
import org.scalatest.{BeforeAndAfterAll, FunSpec, Matchers}
import test.utils.root.{SparkKernelClientDeployer, SparkKernelDeployer}

/**
 * Tests all stdin-related functionality between the client and kernel.
 */
class StdinForSystemSpec extends FunSpec with Matchers with BeforeAndAfterAll
  with Eventually
{
  implicit override val patienceConfig = PatienceConfig(
    timeout = scaled(Span(10, Seconds)),
    interval = scaled(Span(50, Milliseconds))
  )
  private val TestReplyString = "some value"

  private var client: SparkKernelClient = _

  // TODO: Enable once client and kernel have Akka versions that are matching
  // NOTE: This should be the case once we move to 1.2.1 as the Akka version
  //       was updated in Apache Spark to 2.3.4
  /*override protected def beforeAll(): Unit = {
    // Ensure that our one-time initialization happens
    SparkKernelDeployer.startInstance

    client = SparkKernelClientDeployer.startInstance
  }*/

  describe("Stdin for System") {
    describe("when the kernel requests input") {
      ignore("should receive input based on the client's response function") {
        var response: String = ""
        client.setResponseFunction((_, _) => TestReplyString)

        // Read in a chunk of data (our reply string) and return it as a string
        // to be verified by the test
        client.execute(
          """
            |var result: Array[Byte] = Array()
            |val in = kernel.in
            |do {
            |    result = result :+ in.read().toByte
            |} while(in.available() > 0)
            |new String(result)
          """.stripMargin
        ).onResult { result =>
          response = result.data("text/plain")
        }.onError { _ =>
          fail("Client execution to trigger kernel input request failed!")
        }

        eventually {
          response should contain (TestReplyString)
        }
      }
    }
  }

}


text:
recurrent-title: "Cribbage club"
recurrent-description: 'Free to attend and open to learners, improvers and experienced players. Please bring a board if you have one. Call Lisa on 01986 894172 for more information.'
recurrent-day: some Thursdays
recurrent-times: 1100
recurrent-location: bungay-community-library
recurrent-location-display-name: Bungay Community Library
recurrent-location-display-url: /branches/bungay-library/
recurrent-category: arts-crafts-games
---


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('carts', '0008_auto_20160610_1238'),
    ]

    operations = [
        migrations.AddField(
            model_name='cart',
            name='tax_total',
            field=models.DecimalField(default=0.0, max_digits=50, decimal_places=2),
        ),
        migrations.AddField(
            model_name='cart',
            name='total',
            field=models.DecimalField(default=0.0, max_digits=50, decimal_places=2),
        ),
    ]


text:
@interface CCDataBasehandle : NSObject

#pragma mark--- 数据库单列的对象 用的时候用单列创建
+(CCDataBasehandle *) sharedDataBasehandle;

#pragma mark---创建一个表 或者 打开已经创建的表 根据表的名字和运行时的model对象的类 创建一个表!
-(void)createtableName:(NSString *)name Modelclass:(Class)modelClass;

#pragma mark--- 插入一个model 这个model是开始创建表那个modelClass类的对象!
-(void)insertIntoTableModel:(id )model;

#pragma mark--- 删除一个 model 这个model是开始创建表那个modelClass类的对象!
-(void)deleteFromTableModel:(id )model;

#pragma mark--- 取出这个表的所有的model 返回model对象的数组
-(NSMutableArray *)selectAllModel;

#pragma mark--- 更新表中 modelClass 所对应属性的值
#pragma mark--- attributeName:属性的名字 如 @"name"
#pragma mark--- oldname:      属性值没改变之前的值 如 @"张三"
#pragma mark--- newstring:    属性改变之后的值 如 @"李四"
-(void)updateFromAttributeName:(NSString *)attributeName Oldstring:(NSString *)oldname NewString:(NSString *)newstring;

#pragma mark---查找出来 属性值的model数组
#pragma mark--- attributeName:属性的名字 如 @"sex"
#pragma mark--- valueStr:     这个属性对应的值 如 @"男" 那么就会返回 所有@"sex"属性为@"男"的模型数组
-(NSMutableArray *)selectFromAttributeName:(NSString *)attributeName ValueStr:(NSString *)valueStr;

#pragma mark--- 删除一张表
-(void)DeleteTbaleName:(NSString *)tableName;
@end


text:
remote_file "/tmp/epel-release-7-5.noarch.rpm" do
  source "ftp://ftp.muug.mb.ca/mirror/fedora/epel/7/x86_64/e/epel-release-7-5.noarch.rpm"
  owner "root"
  group "root"
  mode "0644"
  action :create
  only_if { mirrors_reachable? }
end

remote_file "/tmp/python-pygments-1.4-9.el7.noarch.rpm" do
  source "ftp://ftp.muug.mb.ca/mirror/centos/7.1.1503/os/x86_64/Packages/python-pygments-1.4-9.el7.noarch.rpm"
  owner "root"
  group "root"
  mode "0644"
  action :create
  only_if { mirrors_reachable? }
end

package "epel-release-7-5" do
  action :install
  source "/tmp/epel-release-7-5.noarch.rpm"
  provider Chef::Provider::Package::Rpm
  only_if { mirrors_reachable? }
end

package "python-imaging" do
  action :install
  only_if { mirrors_reachable? }
end

package "python-pygments" do
  action :install
  source "/tmp/python-pygments-1.4-9.el7.noarch.rpm"
  provider Chef::Provider::Package::Rpm
  only_if { mirrors_reachable? }
end


text:
winApp = null;

chrome.app.runtime.onLaunched.addListener(function() {
	chrome.app.window.create('index.html',{
		'bounds': {
			'width': 1024,
			'height': 700
		}
	});
});


text:
@implementation NSMutableArray (Socialize)

- (void)removeObjectsFromIndex:(NSUInteger)index {
    NSUInteger count = [self count];
    NSAssert(index < count, @"Index out of bounds");
    NSUInteger size = count - index;
    NSAssert(size > 0, @"Size not larger than 0");

    NSRange range = NSMakeRange(index, size);
    [self removeObjectsInRange:range];
}

- (void)removeObjectsAfterIndex:(NSUInteger)index {
    [self removeObjectsFromIndex:index + 1];
}

- (void)removeObjectsAfterObject:(id)object {
    NSUInteger index = [self indexOfObject:object];
    [self removeObjectsAfterIndex:index];
}

@end


text:
package com.yahoo.pasc.paxos.messages;

import java.io.Serializable;
import java.util.Arrays;
import java.util.List;

import com.yahoo.pasc.CloneableDeep;
import com.yahoo.pasc.EqualsDeep;
import com.yahoo.pasc.paxos.state.PaxosState;

public class Digest extends PaxosMessage implements Serializable, CloneableDeep<Digest>, EqualsDeep<Digest>{

    private static final long serialVersionUID = -3781061394615967506L;

    public static class Descriptor implements PaxosDescriptor, EqualsDeep<Descriptor> {

        private long digestId;
        private long digest;

        public Descriptor(long digestId, long digest) {
            this.digestId = digestId;
            this.digest = digest;
        }

        @Override
        public List<PaxosMessage> buildMessages(PaxosState state) {
            return Arrays.<PaxosMessage>asList(new Digest(state.getServerId(), digestId, digest));
        }

        @Override
        public boolean equalsDeep(Descriptor other) {
            return this.digestId == other.digestId && this.digest == other.digest;
        }

    }

    int senderId;
    long digestId;
    long digest;

    public Digest() {
    }

    public Digest(int senderId, long digestId, long digest) {
        this.senderId = senderId;
        this.digestId = digestId;
        this.digest = digest;
    }

    public int getSenderId() {
        return senderId;
    }

    public void setSenderId(int senderId) {
        this.senderId = senderId;
    }

    public long getDigestId() {
        return digestId;
    }

    public void setDigestId(long digestId) {
        this.digestId = digestId;
    }

    public long getDigest() {
        return digest;
    }

    public void setDigest(long digest) {
        this.digest = digest;
    }

    @Override
    public String toString() {
        return String.format("{Digest %s sent from %d for iid %d}", digest, senderId, digestId);
    }

    public Digest cloneDeep(){
    	return new Digest(this.senderId, digestId, digest);
    }

    public boolean equalsDeep (Digest other){
    	return other != null && this.senderId == other.senderId && this.digestId == other.digestId && this.digest == other.digest;
    }
}


text:
import unittest2

from google.appengine.api import taskqueue
from google.appengine.ext import testbed

from models.notifications.requests.request import Request

from tests.mocks.notifications.mock_notification import MockNotification

class TestRequest(unittest2.TestCase):

    def setUp(self):
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_taskqueue_stub(root_path='.')
        self.taskqueue_stub = self.testbed.get_stub(testbed.TASKQUEUE_SERVICE_NAME)

    def tearDown(self):
        self.testbed.deactivate()

    def test_init(self):
        Request(MockNotification())

    def test_send(self):
        request = Request(MockNotification())
        with self.assertRaises(NotImplementedError):
            request.send()

    def test_defer_track_notification(self):
        request = Request(MockNotification())
        request.defer_track_notification(2)
        tasks = self.taskqueue_stub.GetTasks('api-track-call')

        self.assertEqual(len(tasks), 1)
        task = tasks[0]
        self.assertEqual(task['url'], '/_ah/queue/deferred_notification_track_send')
        self.assertEqual(task['queue_name'], 'api-track-call')


text:
package com.dl7.mvp.adapter;

import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.ImageView;

import com.dl7.mvp.R;
import com.dl7.mvp.adapter.item.SpecialItem;
import com.dl7.mvp.api.NewsUtils;
import com.dl7.mvp.module.news.article.NewsArticleActivity;
import com.dl7.mvp.module.news.photoset.PhotoSetActivity;
import com.dl7.mvp.module.news.special.SpecialActivity;
import com.dl7.mvp.utils.DefIconFactory;
import com.dl7.mvp.utils.ImageLoader;
import com.dl7.mvp.utils.StringUtils;
import com.dl7.recycler.adapter.BaseSectionQuickAdapter;
import com.dl7.recycler.adapter.BaseViewHolder;
import com.flyco.labelview.LabelView;

import java.util.List;

/**
 * Created by long on 2016/8/26.
 * 专题列表适配器
 */
public class SpecialAdapter extends BaseSectionQuickAdapter<SpecialItem> {

    public SpecialAdapter(Context context, List<SpecialItem> data) {
        super(context, data);
    }

    public SpecialAdapter(Context context) {
        super(context);
    }

    @Override
    protected int attachLayoutRes() {
        return R.layout.adapter_news_list;
    }

    @Override
    protected int attachHeadLayoutRes() {
        return R.layout.adapter_special_head;
    }

    @Override
    protected void convertHead(BaseViewHolder holder, SpecialItem item) {
        holder.setText(R.id.tv_head, item.header);
    }

    @Override
    protected void convert(BaseViewHolder holder, final SpecialItem item) {
        ImageView newsIcon = holder.getView(R.id.iv_icon);
        ImageLoader.loadCenterCrop(mContext, item.t.getImgsrc(), newsIcon, DefIconFactory.provideIcon());
        holder.setText(R.id.tv_title, item.t.getTitle())
                .setText(R.id.tv_source, StringUtils.clipNewsSource(item.t.getSource()))
                .setText(R.id.tv_time, item.t.getPtime());

        if (NewsUtils.isNewsSpecial(item.t.getSkipType())) {
            LabelView labelView = holder.getView(R.id.label_view);
            labelView.setVisibility(View.VISIBLE);
            labelView.setBgColor(ContextCompat.getColor(mContext, R.color.item_special_bg));
            labelView.setText("专题");
        } else if (NewsUtils.isNewsPhotoSet(item.t.getSkipType())) {
            LabelView labelView = holder.getView(R.id.label_view);
            labelView.setVisibility(View.VISIBLE);
            labelView.setBgColor(ContextCompat.getColor(mContext, R.color.item_photo_set_bg));
            labelView.setText("图集");
        } else {
            holder.setVisible(R.id.label_view, false);
        }

        holder.getConvertView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (NewsUtils.isNewsSpecial(item.t.getSkipType())) {
                    SpecialActivity.launch(mContext, item.t.getSpecialID());
                } else if (NewsUtils.isNewsPhotoSet(item.t.getSkipType())) {
                    PhotoSetActivity.launch(mContext, item.t.getPhotosetID());
                } else {
//                    NewsDetailActivity.launch(mContext, item.t.getPostid());
                    NewsArticleActivity.launch(mContext, item.t.getPostid());
                }
            }
        });
    }
}


text:
package com.kotcrab.vis.editor.util.async;

import com.badlogic.gdx.Gdx;
import com.kotcrab.vis.editor.Log;
import com.kotcrab.vis.editor.ui.dialog.AsyncTaskProgressDialog;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Task that can be executed on another thread.
 * @author Kotcrab
 * @see AsyncTaskProgressDialog
 * @see AsyncTaskListener
 */
public abstract class AsyncTask {
	private Thread thread;
	private Runnable runnable;

	private int progressPercent;
	private String message;

	private AsyncTaskListener listener;

	public AsyncTask (String threadName) {
		runnable = () -> {
			try {
				execute();
			} catch (Exception e) {
				Log.exception(e);
				failed(e.getMessage(), e);
			}

			if (listener != null) listener.finished();
		};
		thread = new Thread(runnable, threadName);
	}

	public void start () {
		thread.start();
	}

	public void failed (String reason) {
		if (listener != null) listener.failed(reason);
	}

	public void failed (String reason, Exception ex) {
		if (listener != null) listener.failed(reason, ex);
	}

	public abstract void execute () throws Exception;

	/**
	 * Executes runnable on OpenGL thread. This methods blocks until runnable finished executing. Note that this
	 * will also block main render thread.
	 */
	protected void executeOnOpenGL (final Runnable runnable) {
		final CountDownLatch latch = new CountDownLatch(1);

		AtomicReference<Exception> exceptionAt = new AtomicReference<>();

		Gdx.app.postRunnable(() -> {
			try {
				runnable.run();
			} catch (Exception e) {
				Log.exception(e);
				exceptionAt.set(e);
			}
			latch.countDown();
		});

		try {
			latch.await();

			Exception e = exceptionAt.get();
			if (e != null) {
				failed(e.getMessage(), e);
			}
		} catch (InterruptedException e) {
			Log.exception(e);
		}
	}

	public int getProgressPercent () {
		return progressPercent;
	}

	public void setProgressPercent (int progressPercent) {
		this.progressPercent = progressPercent;
		if (listener != null) listener.progressChanged(progressPercent);
	}

	public void setRunnable (Runnable runnable) {
		this.runnable = runnable;
	}

	public String getMessage () {
		return message;
	}

	public void setMessage (String message) {
		this.message = message;
		if (listener != null) listener.messageChanged(message);
	}

	public void setListener (AsyncTaskListener listener) {
		this.listener = listener;
	}
}


text:
// Write a program that reads two arrays from the console and compares them element by element.

using System;

class CompareTwoArrays
{
    static void Main()
    {
        Console.WriteLine("Enter the elements of two arrays on two different lines. The elements must be integer numbers, separated by an interval");
        Console.WriteLine("Enter the elements of the first array");
        string inputArrayOne = Console.ReadLine();
        Console.WriteLine("Enter the elements of the second array");
        string inputArrayTwo = Console.ReadLine();

        // Transforming the input string into a string array
        string[] inputOne = inputArrayOne.Split(' '); //the intervals between the elements are used as separators.

        string[] inputTwo = inputArrayTwo.Split(' ');

        //Parsing
        int[] array1 = new int[inputOne.Length];
        for (int i = 0; i < inputOne.Length; i++)
        {
            array1[i] = int.Parse(inputOne[i]);
        }
        int[] array2 = new int[inputTwo.Length];
        for (int i = 0; i < inputTwo.Length; i++)
        {
            array2[i] = int.Parse(inputTwo[i]);
        }

        //Comparing array1 and array2
        int counter = 0;
        if (array1.Length != array2.Length)
        {
            Console.WriteLine("The two arrays are not equal");
        }
        else if (array1.Length == array2.Length)
        {
            for (int i = 0; i < array1.Length; i++)
            {
                if (array1[i] == array2[i])
                {
                    counter++;
                }
            }
            if (counter == array1.Length)
            {
                Console.WriteLine("The two arrays are equal!");
            }
            else
	        {
                Console.WriteLine("The two arrays are NOT equal!");
	        }
        }
    }
}


text:
'use strict';

module.exports = function (grunt) {

    // Project configuration.
    grunt.initConfig({
        watch: {
            test: {
                files: ['**/*.js'],
                tasks: ['mochaTest'],
                options: {
                    spawn: true
                }
            }
        },

        mochaTest: {
            test: {
                options: {
                    reporter: 'spec'
                },
                src: ['test/**/*.js']
            }
        }
    });

    // These plugins provide necessary tasks.
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-mocha-test');

    grunt.registerTask('test', 'mochaTest');
    grunt.registerTask('watch-test', 'watch');

};


text:
layout: post
title:  "Configurar GIT (BitBucket) en Visual Studio 2010 y no morir en el intento"
date:   2012-03-10
categories: [Ingeniería del Software, Source Control]
tags: [BitBucket,GIT,Tutorial,Visual Studio 2010]
---
Que **Git** se ha convertido en el más famoso y mejor **controlador de versiones de código** es una cosa que ya sabéis pero, ¿cómo puedo **configurar las herramientas** necesarias para poder **trabajar** con un **repositorio Git en mi Visual Studio 2010**?

El objetivo de este pequeño tutorial es conseguirlo sin morir en el intento

Nota: Este tutorial no explica el funcionamiento de un control de versiones por lo que doy por supuesto que todo el mundo sabe lo que es un commit, push, pull, branch, etc… Otro día haré un artículo dedicado a explicar más a fondo como funciona un control de versiones ! :)

## ¿BitBucket o GitHub?

¡Para empezar! Necesitamos una cuenta en algún servicio de repositorio de Git (si no dispones de uno local o el de tu empresa).

Actualmente existen dos grandes servicios gratuitos de Git que son **[GitHub](https://github.com/)** y **[BitBucket](https://bitbucket.org/)**. No voy a entrar a discutir cual es mejor en este artículo, solo diré que **BitBucket** te permite tener, **de forma gratuita**, **repositorios privados** lo cual es perfecto para esas pequeñas aplicaciones que tienes en casa y quieres salvaguardar.

Es por este motivo principalmente por lo que yo uso BitBucket como Source Control !

¿Ya tienes cuenta en **BitBucket**? ¡Descarguemos Git!

## Descargando y Configurando Git para Windows

Bien, lo primero que necesitamos es descargar Git para Windows el cual podemos encontrar aquí: **[http://code.google.com/p/msysgit/downloads/list](http://code.google.com/p/msysgit/downloads/list)**

Descarga e instala la última versión disponible.

No hay que modificar casi nada durante el proceso de instalación. La única opción que recomiendo modificar es la de "Adjusing your PATH environment" la cual aconsejo cambiar de "Use Git Bash only" a "Run git from the Windows Command Prompt" tal y como se ve en la siguiente captura:

 ![](http://res.cloudinary.com/escapistasclub/image/upload/v1470207921/Compilando/git_1.png)

El resto lo puedes dejar igual.

¡Bien! ¡Ya lo tenemos instalado! Ahora tenemos que configurarlo para que funcione con nuestra cuenta de BitBucktet.

Para ello ejecutamos el "**Git Bash**" (si, es una consola, no te asustes, jeje) e introducimos la configuración global de nuestro usuario de BitBucket e Email escribiendo:

```bash
git config --global user.name "tu usuario de BitBucket aquí"
git config --globla user.email "tu email de BitBucket aquí"
```

![](http://res.cloudinary.com/escapistasclub/image/upload/v1470207927/Compilando/git2.png)

Con esto ya lo tenemos!

Ahora vamos a configurar las herramientas en el Visual Studio 2010.

## Configurando Git en Visual Studio 2010

Debido a que **Visual Studio** no incluye Git como control de código por defecto (solo incluye SourceSafe y Team Foundation Server) necesitamos instalar una pequeña extensión de Git para que funcione.
Para ello vamos a "**Tools > Extension Manager**" o "**Herramientas > Administrador de Extensiones**" en castellano y, en la Galería Online buscamos "Git" para instalar el "**Git Source Control Provider**":

![](http://res.cloudinary.com/escapistasclub/image/upload/v1470207929/Compilando/git3.png)

Una vez instalado lo escogemos como Source Control por defecto en **"Herramientas > Opciones > Source Control > Selección de Complemento > Git Source Control Provider"**

Lo próximo que debemos hacer es abrir (o crear) la solución que queremos subir a BitBucket y, pulsando botón derecho sobre el nombre de la solución clickamos en "**New Repository**".

Esto creará un nuevo repositorio Git en el mismo directorio en el que está la solución.

Verás que en el "Solution Explorer" aparecen unos símbolos con un "+" amarillo. Esto indica que el fichero es nuevo y no se encuentra en tu repositorio local.

Haciendo click derecho de nuevo sobre la solución y pulsando en "**Pending Changes**" podremos ver el listado de ficheros pendientes, escribir un comentario y hacer el **primer commit** contra tu repositorio local.

¡Ya está! ¡Ya tenemos configurado Git para Visual Studio! Eso si, de momento solo lo deja en local y BitBucket ni lo hemos usado.

¿Qué toca ahora? **Configurar Git Bash para que suba nuestros commits a BitBucket.**

## Configurar Remote y hacer Push desde Visual Studio a BitBucket

De nuevo **botón derecho en la solución > Pending Changes > Git Bash** y se nos abrirá la consola de Git. Ahora tenemos que configurar el acceso remoto.

Para ello escribimos lo siguiente:

`git remote add origin https://usuario@bitbucket.org/nombre_del_repositorio.git`

Supongamos que mi usuario es "vfportero" y mi repositorio en BitBucket se llama "demo". El remote sería así:

`git remote add origin https://vfportero@bitbucket.org/demo.git`

¡Perfecto! Con esto ya podemos escribir:

`git push`

Nos pedirá el password de BitBucket y, una vez escrito, y el bash solito se encargará de subir los ficheros al repositorio remoto.

Espero que os haya servido de ayuda.

**¡Nos vemos Compilando!**


text:
// Copyright 2007-2016 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.Pipeline.Observables
{
    using System.Threading.Tasks;
    using GreenPipes.Util;

    public class ReceiveTransportObservable :
        Connectable<IReceiveTransportObserver>,
        IReceiveTransportObserver
    {
        public Task Ready(ReceiveTransportReady ready)
        {
            return ForEachAsync(x => x.Ready(ready));
        }

        public Task Completed(ReceiveTransportCompleted completed)
        {
            return ForEachAsync(x => x.Completed(completed));
        }

        public Task Faulted(ReceiveTransportFaulted faulted)
        {
            return ForEachAsync(x => x.Faulted(faulted));
        }
    }
}


text:
using System;
using System.ComponentModel;

namespace Azure.ResourceManager.HealthcareApis.Models
{
    /// <summary> Control permission for data plane traffic coming from public networks while private endpoint is enabled. </summary>
    public readonly partial struct HealthcareApisPublicNetworkAccess : IEquatable<HealthcareApisPublicNetworkAccess>
    {
        private readonly string _value;

        /// <summary> Initializes a new instance of <see cref="HealthcareApisPublicNetworkAccess"/>. </summary>
        /// <exception cref="ArgumentNullException"> <paramref name="value"/> is null. </exception>
        public HealthcareApisPublicNetworkAccess(string value)
        {
            _value = value ?? throw new ArgumentNullException(nameof(value));
        }

        private const string EnabledValue = "Enabled";
        private const string DisabledValue = "Disabled";

        /// <summary> Enabled. </summary>
        public static HealthcareApisPublicNetworkAccess Enabled { get; } = new HealthcareApisPublicNetworkAccess(EnabledValue);
        /// <summary> Disabled. </summary>
        public static HealthcareApisPublicNetworkAccess Disabled { get; } = new HealthcareApisPublicNetworkAccess(DisabledValue);
        /// <summary> Determines if two <see cref="HealthcareApisPublicNetworkAccess"/> values are the same. </summary>
        public static bool operator ==(HealthcareApisPublicNetworkAccess left, HealthcareApisPublicNetworkAccess right) => left.Equals(right);
        /// <summary> Determines if two <see cref="HealthcareApisPublicNetworkAccess"/> values are not the same. </summary>
        public static bool operator !=(HealthcareApisPublicNetworkAccess left, HealthcareApisPublicNetworkAccess right) => !left.Equals(right);
        /// <summary> Converts a string to a <see cref="HealthcareApisPublicNetworkAccess"/>. </summary>
        public static implicit operator HealthcareApisPublicNetworkAccess(string value) => new HealthcareApisPublicNetworkAccess(value);

        /// <inheritdoc />
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override bool Equals(object obj) => obj is HealthcareApisPublicNetworkAccess other && Equals(other);
        /// <inheritdoc />
        public bool Equals(HealthcareApisPublicNetworkAccess other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase);

        /// <inheritdoc />
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override int GetHashCode() => _value?.GetHashCode() ?? 0;
        /// <inheritdoc />
        public override string ToString() => _value;
    }
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Senecio callacallensis Cuatrec.

### Remarks
null


text: ALTER TABLE HIVE_LOCKS ADD COLUMN HL_AGENT_INFO varchar(128);


text:
package io.piotrjastrzebski.monster.game.components;

import com.artemis.PooledComponent;

/**
 * Created by PiotrJ on 22/08/15.
 */
public class Shoot extends PooledComponent {
	public float dmg;
	public float delay;
	public float timer;
	public float dst;

	@Override protected void reset () {
		dmg = 0;
		dst = 0;
		delay = 0;
		timer = 0;
	}

	public Shoot dmg (float dmg) {
		this.dmg = dmg;
		return this;
	}

	public Shoot dst (float dst) {
		this.dst = dst;
		return this;
	}

	public Shoot delay (float delay) {
		this.delay = delay;
		return this;
	}
}


text:
import React from 'react';

class PureComponentName extends React.PureComponent {
    render() {
        return

Hello world

;
    }
}

export default PureComponentName;