text:
from __future__ import annotations
from typing import TYPE_CHECKING, Tuple, Optional
import math

from ezdxf.lldxf import validator
from ezdxf.lldxf import const
from ezdxf.lldxf.attributes import (
    DXFAttr,
    DXFAttributes,
    DefSubclass,
    XType,
    RETURN_DEFAULT,
    group_code_mapping,
    merge_group_code_mappings,
)
from ezdxf.enums import (
    TextEntityAlignment,
    MAP_TEXT_ENUM_TO_ALIGN_FLAGS,
    MAP_TEXT_ALIGN_FLAGS_TO_ENUM,
)
from ezdxf.math import Vec3, UVec, Matrix44, NULLVEC, Z_AXIS
from ezdxf.math.transformtools import OCSTransform
from ezdxf.audit import Auditor
from ezdxf.tools.text import plain_text

from .dxfentity import base_class, SubclassProcessor
from .dxfgfx import (
    DXFGraphic,
    acdb_entity,
    elevation_to_z_axis,
    acdb_entity_group_codes,
)
from .factory import register_entity

if TYPE_CHECKING:
    from ezdxf.document import Drawing
    from ezdxf.entities import DXFNamespace
    from ezdxf.lldxf.tagwriter import AbstractTagWriter

__all__ = ["Text", "acdb_text", "acdb_text_group_codes"]

acdb_text = DefSubclass(
    "AcDbText",
    {
        # First alignment point (in OCS):
        "insert": DXFAttr(10, xtype=XType.point3d, default=NULLVEC),
        # Text height
        "height": DXFAttr(
            40,
            default=2.5,
            validator=validator.is_greater_zero,
            fixer=RETURN_DEFAULT,
        ),
        # Text content as string:
        "text": DXFAttr(
            1,
            default="",
            validator=validator.is_valid_one_line_text,
            fixer=validator.fix_one_line_text,
        ),
        # Text rotation in degrees (optional)
        "rotation": DXFAttr(50, default=0, optional=True),
        # Oblique angle in degrees, vertical = 0 deg (optional)
        "oblique": DXFAttr(51, default=0, optional=True),
        # Text style name (optional), given text style must have an entry in the
        # text-styles tables.
        "style": DXFAttr(7, default="Standard", optional=True),
        # Relative X scale factor—width (optional)
        # This value is also adjusted when fit-type text is used
        "width": DXFAttr(
            41,
            default=1,
            optional=True,
            validator=validator.is_greater_zero,
            fixer=RETURN_DEFAULT,
        ),
        # Text generation flags (optional)
        # 2 = backward (mirror-x),
        # 4 = upside down (mirror-y)
        "text_generation_flag": DXFAttr(
            71,
            default=0,
            optional=True,
            validator=validator.is_one_of({0, 2, 4, 6}),
            fixer=RETURN_DEFAULT,
        ),
        # Horizontal text justification type (optional) horizontal justification
        # 0 = Left
        # 1 = Center
        # 2 = Right
        # 3 = Aligned (if vertical alignment = 0)
        # 4 = Middle (if vertical alignment = 0)
        # 5 = Fit (if vertical alignment = 0)
        # This value is meaningful only if the value of a 72 or 73 group is nonzero
        # (if the justification is anything other than baseline/left)
        "halign": DXFAttr(
            72,
            default=0,
            optional=True,
            validator=validator.is_in_integer_range(0, 6),
            fixer=RETURN_DEFAULT,
        ),
        # Second alignment point (in OCS) (optional)
        "align_point": DXFAttr(11, xtype=XType.point3d, optional=True),
        # Elevation is a legacy feature from R11 and prior, do not use this
        # attribute, store the entity elevation in the z-axis of the vertices.
        # ezdxf does not export the elevation attribute!
        "elevation": DXFAttr(38, default=0, optional=True),
        # Thickness in extrusion direction, only supported for SHX font in
        # AutoCAD/BricsCAD (optional), can be negative
        "thickness": DXFAttr(39, default=0, optional=True),
        # Extrusion direction (optional)
        "extrusion": DXFAttr(
            210,
            xtype=XType.point3d,
            default=Z_AXIS,
            optional=True,
            validator=validator.is_not_null_vector,
            fixer=RETURN_DEFAULT,
        ),
    },
)
acdb_text_group_codes = group_code_mapping(acdb_text)
acdb_text2 = DefSubclass(
    "AcDbText",
    {
        # Vertical text justification type (optional)
        # 0 = Baseline
        # 1 = Bottom
        # 2 = Middle
        # 3 = Top
        "valign": DXFAttr(
            73,
            default=0,
            optional=True,
            validator=validator.is_in_integer_range(0, 4),
            fixer=RETURN_DEFAULT,
        )
    },
)
acdb_text2_group_codes = group_code_mapping(acdb_text2)
merged_text_group_codes = merge_group_code_mappings(
    acdb_entity_group_codes,  # type: ignore
    acdb_text_group_codes,
    acdb_text2_group_codes,
)

# Formatting codes:
# %%d: '°'
# %%u in TEXT start underline formatting until next %%u or until end of line

@register_entity
class Text(DXFGraphic):
    """DXF TEXT entity"""

    DXFTYPE = "TEXT"
    DXFATTRIBS = DXFAttributes(base_class, acdb_entity, acdb_text, acdb_text2)
    # horizontal align values
    LEFT = 0
    CENTER = 1
    RIGHT = 2
    # vertical align values
    BASELINE = 0
    BOTTOM = 1
    MIDDLE = 2
    TOP = 3
    # text generation flags
    MIRROR_X = 2
    MIRROR_Y = 4
    BACKWARD = MIRROR_X
    UPSIDE_DOWN = MIRROR_Y

    def load_dxf_attribs(
        self, processor: Optional[SubclassProcessor] = None
    ) -> DXFNamespace:
        """Loading interface. (internal API)"""
        dxf = super(DXFGraphic, self).load_dxf_attribs(processor)
        if processor:
            processor.simple_dxfattribs_loader(dxf, merged_text_group_codes)
            if processor.r12:
                # Transform elevation attribute from R11 to z-axis values:
                elevation_to_z_axis(dxf, ("insert", "align_point"))
        return dxf

    def export_entity(self, tagwriter: AbstractTagWriter) -> None:
        """Export entity specific data as DXF tags. (internal API)"""
        super().export_entity(tagwriter)
        self.export_acdb_text(tagwriter)
        self.export_acdb_text2(tagwriter)

    def export_acdb_text(self, tagwriter: AbstractTagWriter) -> None:
        """Export TEXT data as DXF tags. (internal API)"""
        if tagwriter.dxfversion > const.DXF12:
            tagwriter.write_tag2(const.SUBCLASS_MARKER, acdb_text.name)
        self.dxf.export_dxf_attribs(
            tagwriter,
            [
                "insert",
                "height",
                "text",
                "thickness",
                "rotation",
                "oblique",
                "style",
                "width",
                "text_generation_flag",
                "halign",
                "align_point",
                "extrusion",
            ],
        )

    def export_acdb_text2(self, tagwriter: AbstractTagWriter) -> None:
        """Export TEXT data as DXF tags. (internal API)"""
        if tagwriter.dxfversion > const.DXF12:
            tagwriter.write_tag2(const.SUBCLASS_MARKER, acdb_text2.name)
        self.dxf.export_dxf_attribs(tagwriter, "valign")

    def set_placement(
        self,
        p1: UVec,
        p2: Optional[UVec] = None,
        align: Optional[TextEntityAlignment] = None,
    ) -> Text:
        """Set text alignment and location.

        The alignments :attr:`ALIGNED` and :attr:`FIT`
        are special, they require a second alignment point, the text is aligned
        on the virtual line between these two points and sits vertically at the
        baseline.

        - :attr:`ALIGNED`: Text is stretched or compressed
          to fit exactly between `p1` and `p2` and the text height is also
          adjusted to preserve height/width ratio.
        - :attr:`FIT`: Text is stretched or compressed to fit
          exactly between `p1` and `p2` but only the text width is adjusted,
          the text height is fixed by the :attr:`dxf.height` attribute.
        - :attr:`MIDDLE`: also a special adjustment, centered
          text like :attr:`MIDDLE_CENTER`, but vertically
          centred at the total height of the text.

        Args:
            p1: first alignment point as (x, y[, z])
            p2: second alignment point as (x, y[, z]), required for :attr:`ALIGNED`
                and :attr:`FIT` else ignored
            align: new alignment as enum :class:`~ezdxf.enums.TextEntityAlignment`,
                ``None`` to preserve the existing alignment.

        """
        if align is None:
            align = self.get_align_enum()
        else:
            assert isinstance(align, TextEntityAlignment)
            self.set_align_enum(align)
        self.dxf.insert = p1
        if align in (TextEntityAlignment.ALIGNED, TextEntityAlignment.FIT):
            if p2 is None:
                raise const.DXFValueError(
                    f"Alignment '{str(align)}' requires a second alignment point."
                )
        else:
            p2 = p1
        self.dxf.align_point = p2
        return self

    def get_placement(self) -> Tuple[TextEntityAlignment, Vec3, Optional[Vec3]]:
        """Returns a tuple (`align`, `p1`, `p2`), `align` is the alignment
        enum :class:`~ezdxf.enum.TextEntityAlignment`, `p1` is the
        alignment point, `p2` is only relevant if `align` is :attr:`ALIGNED` or
        :attr:`FIT`, otherwise it is ``None``.

        """
        p1 = Vec3(self.dxf.insert)
        # Except for "LEFT" is the "align point" the real insert point:
        # If the required "align point" is not present use "insert"!
        p2 = Vec3(self.dxf.get("align_point", p1))
        align = self.get_align_enum()
        if align is TextEntityAlignment.LEFT:
            return align, p1, None
        if align in (TextEntityAlignment.FIT, TextEntityAlignment.ALIGNED):
            return align, p1, p2
        return align, p2, None

    def set_align_enum(self, align=TextEntityAlignment.LEFT) -> Text:
        """Just for experts: Sets the text alignment without setting the
        alignment points, set adjustment points attr:`dxf.insert` and
        :attr:`dxf.align_point` manually.

        Args:
            align: :class:`~ezdxf.enums.TextEntityAlignment`

        """
        halign, valign = MAP_TEXT_ENUM_TO_ALIGN_FLAGS[align]
        self.dxf.halign = halign
        self.dxf.valign = valign
        return self

    def get_align_enum(self) -> TextEntityAlignment:
        """Returns the current text alignment as :class:`~ezdxf.enums.TextEntityAlignment`,
        see also :meth:`set_placement`.
        """
        halign = self.dxf.get("halign", 0)
        valign = self.dxf.get("valign", 0)
        if halign > 2:
            valign = 0
        return MAP_TEXT_ALIGN_FLAGS_TO_ENUM.get(
            (halign, valign), TextEntityAlignment.LEFT
        )

    def transform(self, m: Matrix44) -> Text:
        """Transform the TEXT entity by transformation matrix `m` inplace."""
        dxf = self.dxf
        if not dxf.hasattr("align_point"):
            dxf.align_point = dxf.insert
        ocs = OCSTransform(self.dxf.extrusion, m)
        dxf.insert = ocs.transform_vertex(dxf.insert)
        dxf.align_point = ocs.transform_vertex(dxf.align_point)
        old_rotation = dxf.rotation
        new_rotation = ocs.transform_deg_angle(old_rotation)
        x_scale = ocs.transform_length(Vec3.from_deg_angle(old_rotation))
        y_scale = ocs.transform_length(Vec3.from_deg_angle(old_rotation + 90.0))

        if not ocs.scale_uniform:
            oblique_vec = Vec3.from_deg_angle(old_rotation + 90.0 - dxf.oblique)
            new_oblique_deg = (
                new_rotation
                + 90.0
                - ocs.transform_direction(oblique_vec).angle_deg
            )
            dxf.oblique = new_oblique_deg
            y_scale *= math.cos(math.radians(new_oblique_deg))

        dxf.width *= x_scale / y_scale
        dxf.height *= y_scale
        dxf.rotation = new_rotation

        if dxf.hasattr("thickness"):  # can be negative
            dxf.thickness = ocs.transform_thickness(dxf.thickness)
        dxf.extrusion = ocs.new_extrusion
        self.post_transform(m)
        return self

    def translate(self, dx: float, dy: float, dz: float) -> Text:
        """Optimized TEXT/ATTRIB/ATTDEF translation about `dx` in x-axis, `dy`
        in y-axis and `dz` in z-axis, returns `self`.

        """
        ocs = self.ocs()
        dxf = self.dxf
        vec = Vec3(dx, dy, dz)

        dxf.insert = ocs.from_wcs(vec + ocs.to_wcs(dxf.insert))
        if dxf.hasattr("align_point"):
            dxf.align_point = ocs.from_wcs(vec + ocs.to_wcs(dxf.align_point))
        # Avoid Matrix44 instantiation if not required:
        if self.is_post_transform_required:
            self.post_transform(Matrix44.translate(dx, dy, dz))
        return self

    def remove_dependencies(self, other: Optional[Drawing] = None) -> None:
        """Remove all dependencies from actual document.

        (internal API)
        """
        if not self.is_alive:
            return

        super().remove_dependencies()
        has_style = other is not None and (self.dxf.style in other.styles)
        if not has_style:
            self.dxf.style = "Standard"

    def plain_text(self) -> str:
        """Returns text content without formatting codes."""
        return plain_text(self.dxf.text)

    def audit(self, auditor: Auditor):
        """Validity check."""
        super().audit(auditor)
        auditor.check_text_style(self)

    @property
    def is_backward(self) -> bool:
        """Get/set text generation flag BACKWARDS, for mirrored text along the
        x-axis.
        """
        return bool(self.dxf.text_generation_flag & const.BACKWARD)

    @is_backward.setter
    def is_backward(self, state) -> None:
        self.set_flag_state(const.BACKWARD, state, "text_generation_flag")

    @property
    def is_upside_down(self) -> bool:
        """Get/set text generation flag UPSIDE_DOWN, for mirrored text along
        the y-axis.

        """
        return bool(self.dxf.text_generation_flag & const.UPSIDE_DOWN)

    @is_upside_down.setter
    def is_upside_down(self, state) -> None:
        self.set_flag_state(const.UPSIDE_DOWN, state, "text_generation_flag")

    def wcs_transformation_matrix(self) -> Matrix44:
        return text_transformation_matrix(self)

    def font_name(self) -> str:
        """Returns the font name of the associated :class:`Textstyle`."""
        font_name = "arial.ttf"
        style_name = self.dxf.style
        if self.doc:
            try:
                style = self.doc.styles.get(style_name)
                font_name = style.dxf.font
            except ValueError:
                pass
        return font_name

    def fit_length(self) -> float:
        """Returns the text length for alignments :attr:`TextEntityAlignment.FIT`
        and :attr:`TextEntityAlignment.ALIGNED`, defined by the distance from
        the insertion point to the align point or 0 for all other alignments.

        """
        length = 0.0
        align, p1, p2 = self.get_placement()
        if align in (TextEntityAlignment.FIT, TextEntityAlignment.ALIGNED):
            # text is stretch between p1 and p2
            length = p1.distance(p2)
        return length

def text_transformation_matrix(entity: Text) -> Matrix44:
    """Apply rotation, width factor, translation to the insertion point
    and if necessary transformation from OCS to WCS.
    """
    angle = math.radians(entity.dxf.rotation)
    width_factor = entity.dxf.width
    align, p1, p2 = entity.get_placement()
    mirror_x = -1 if entity.is_backward else 1
    mirror_y = -1 if entity.is_upside_down else 1
    oblique = math.radians(entity.dxf.oblique)
    location = p1
    if align in (TextEntityAlignment.ALIGNED, TextEntityAlignment.FIT):
        width_factor = 1.0  # text goes from p1 to p2, no stretching applied
        location = p1.lerp(p2, factor=0.5)
        angle = (p2 - p1).angle  # override stored angle

    m = Matrix44()
    if oblique:
        m *= Matrix44.shear_xy(angle_x=oblique)
    sx = width_factor * mirror_x
    sy = mirror_y
    if sx != 1 or sy != 1:
        m *= Matrix44.scale(sx, sy, 1)
    if angle:
        m *= Matrix44.z_rotate(angle)
    if location:
        m *= Matrix44.translate(location.x, location.y, location.z)

    ocs = entity.ocs()
    if ocs.transform:  # to WCS
        m *= ocs.matrix
    return m


text:
[unmaintained-url]: .github/ISSUE_TEMPLATE.md
[unmaintained-image]: https://img.shields.io/badge/project-unmaintained-red.svg

[![Project unmaintained][unmaintained-image]][unmaintained-url]
[![PyPI Version](https://badge.fury.io/py/jasy.png)](http://badge.fury.io/py/jasy)

Jasy - Web Tooling Framework
============================

Jasy is a powerful Python3-based tooling framework. It makes it
easy to manage heavy web projects. Its main goal is to offer
an API which could be used by developers to write their custom
build/deployment scripts.

## Installation

For details have a look at [the official documentation](https://github.com/sebastian-software/jasy/wiki).

## Documentation

* [Documentation](http://github.com/sebastian-software/jasy/wiki)
* API Reference: [ReadTheDocs](https://readthedocs.org/projects/jasy/) or [Python.org](http://packages.python.org/jasy/)

## QuickStart

* [Jasy Boilerplate Skeleton](https://github.com/sebastian-software/jasy-html5-boilerplate) with [QuickStart guide](https://github.com/zynga/jasy-html5-boilerplate/wiki/QuickStart) for beginners
* [Core Skeleton](https://github.com/sebastian-software/core): Lightweight skeleton for using Jasy, Core and Api Browser with a set of pre-defined tasks.

## Related

* [Core](http://github.com/sebastian-software/core): Core Library for JavaScript projects. Ideal JS counterpart to Jasy.
* [Jasy Compat](http://github.com/sebastian-software/jasy-compat): Showing how to integrate other JavaScript libraries into Jasy workflow
* [Jasy Locale](https://github.com/sebastian-software/jasy-locale): Demonstrating locale and translation support in Jasy/Core.

## Test Skeletons

* [Jasy Skeleton](http://github.com/sebastian-software/jasy-skeleton): Test skeletons for Jasy using different "jasy create" aspects
* [Jasy Top Level Skeleton](https://github.com/sebastian-software/jasy-toplevelskeleton): Demonstrating how a standalone skeleton might look like.

## License

Copyright (c) 2011-2012 Zynga Inc. http://zynga.com/
Copyright (c) 2012-2014 Sebastian Werner http://sebastian-werner.com

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

redpajama_set_name: RedPajamaGithub


text:
module Google
  module Cloud
    module Vision
      VERSION = "1.2.0"
    end
  end
end


text:
module Proxy.AI.AIControl where
import Control.Concurrent.MVar
import Proxy.Server.Messages
import Settings

type FrameCalculation aiState = GameInfo -> GameState -> [GameState] -> Maybe aiState -> ([Command],Maybe aiState)
type StartCalculation = GameInfo -> GameInfo

aiThread :: MVar GameState -> MVar [Command] -> GameInfo -> FrameCalculation a -> IO ()
aiThread stateVar commVar onStartData onFrame = aiLoop [] Nothing
  where aiLoop history aiState = do
          gameState <- takeMVar stateVar
          let (commands, newAIState) = onFrame onStartData gameState history aiState
          putMVar commVar commands
          let newHistory = history `seq` (take Settings.historyLength (gameState : history))
          aiLoop newHistory newAIState


text:
package com.timeyang.jkes.entity;

import lombok.AllArgsConstructor;
import lombok.Setter;

import javax.persistence.Embeddable;

/**
 * @author chaokunyang
 */
@Embeddable
@Setter
@AllArgsConstructor
public class Car {
    private Long id;
    private String name;

    public Long getId() {
        return id;
    }

    public String getName() {
        return name;
    }
}


text:
require_relative "gems/longhorn-0.1.0/lib/longhorn"
Longhorn.run


text:
package reopp.common.guardedcommands.dataconnectors

import reopp.common.Utils
import Utils._
import reopp.common.guardedcommands._

/**
 * Created with IntelliJ IDEA.
 * User: jose
 * Date: 11/06/12
 * Time: 14:13
 * To change this template use File | Settings | File Templates.
 */

class GCNExRouter(src: String, snks: List[String]) extends GCConnector(src::snks) {
//  def v(x:String) = Var(flowVar(x, uid))

  private def orSnks = genSnkOr(snks)
  private def genSnkOr(lst:List[String]): Guard = lst match {
    case x::Nil => x
    case x::xs  => x or genSnkOr(xs)
    case Nil    => Neg(True)
  }

  private def genSnkAnd(lst:List[String]): Guard = lst match {
    case x::Nil => x
    case x::xs  => x and genSnkAnd(xs)
    case Nil    => True
  }

  private def genData(lst:List[String]): List[GuardedCom] =
    for (snk <- snks) yield snk --> VarAssgn(snk.data,src.data)

  private def c1 = src --> orSnks
  private def c2 = orSnks --> src
  private def c3 = if (snks.tail.isEmpty) True else Neg(genSnkAnd(snks))

  private def constraints = Formula(
    c1,
    c2,
    c3
  )

  private def dataConstraints = constraints ++ genData(snks)

  if (useCC3) throw new Exception("CC3 not implemented")

  def getConstraints = if (useData) dataConstraints else constraints

  //  var constraints = Formula(Set(
//    av --> SGuard(bv or cv),
//    (bv or cv) --> SGuard(av),
//    True --> SGuard(Neg(bv and cv)),
//    bv --> VarAssgn(dataVar(b, uid), dataVar(a, uid)),
//    cv --> VarAssgn(dataVar(c, uid), dataVar(a, uid))
//  ))
}


text: Small Django App and Rest API


text:
require "uri"

module Git
  module Cop
    module Validators
      class Email
        def initialize text, pattern: URI::MailTo::EMAIL_REGEXP
          @text = text
          @pattern = pattern
        end

        def valid?
          String(text).match? pattern
        end

        private

        attr_reader :text, :pattern
      end
    end
  end
end


text:
import {Context, Inject, Middleware} from "@tsed/common";
import {getValue} from "@tsed/core";
import {Unauthorized} from "@tsed/exceptions";
import {promisify} from "util";
import {FormioService} from "../services/FormioService";

/**
 * @middleware
 * @formio
 */
@Middleware()
export class FormioAuthMiddleware {
  @Inject()
  protected formio: FormioService;

  get tokenHandler(): any {
    return promisify(this.formio.middleware.tokenHandler);
  }

  async use(@Context() ctx: Context) {
    const req = ctx.getRequest();
    const res = ctx.getResponse();

    await this.tokenHandler(req, res);

    if (!getValue(req, "token.user._id")) {
      throw new Unauthorized("User unauthorized");
    }
  }
}


text:
#include BOSS_LIBGIT2_U_common_h //original-code:"common.h"
#include "diff.h"
#include "diff_patch.h"
#include "fileops.h"
#include "zstream.h"
#include "blob.h"
#include "delta.h"
#include BOSS_LIBGIT2_U_git2__sys__diff_h //original-code:"git2/sys/diff.h"

typedef struct {
	git_diff *diff;
	git_diff_format_t format;
	git_diff_line_cb print_cb;
	void *payload;
	git_buf *buf;
	uint32_t flags;
	int oid_strlen;
	git_diff_line line;
} diff_print_info;

static int diff_print_info_init(
	diff_print_info *pi,
	git_buf *out,
	git_diff *diff,
	git_diff_format_t format,
	git_diff_line_cb cb,
	void *payload)
{
	pi->diff     = diff;
	pi->format   = format;
	pi->print_cb = cb;
	pi->payload  = payload;
	pi->buf      = out;

	if (diff)
		pi->flags = diff->opts.flags;
	else
		pi->flags = 0;

	if (diff && diff->opts.id_abbrev != 0)
		pi->oid_strlen = diff->opts.id_abbrev;
	else if (!diff || !diff->repo)
		pi->oid_strlen = GIT_ABBREV_DEFAULT;
	else if (git_repository__cvar(
		&pi->oid_strlen, diff->repo, GIT_CVAR_ABBREV) < 0)
		return -1;

	pi->oid_strlen += 1; /* for NUL byte */

	if (pi->oid_strlen < 2)
		pi->oid_strlen = 2;
	else if (pi->oid_strlen > GIT_OID_HEXSZ + 1)
		pi->oid_strlen = GIT_OID_HEXSZ + 1;

	memset(&pi->line, 0, sizeof(pi->line));
	pi->line.old_lineno = -1;
	pi->line.new_lineno = -1;
	pi->line.num_lines  = 1;

	return 0;
}

static char diff_pick_suffix(int mode)
{
	if (S_ISDIR(mode))
		return '/';
	else if (GIT_PERMS_IS_EXEC(mode)) /* -V536 */
		/* in git, modes are very regular, so we must have 0100755 mode */
		return '*';
	else
		return ' ';
}

char git_diff_status_char(git_delta_t status)
{
	char code;

	switch (status) {
	case GIT_DELTA_ADDED:      code = 'A'; break;
	case GIT_DELTA_DELETED:    code = 'D'; break;
	case GIT_DELTA_MODIFIED:   code = 'M'; break;
	case GIT_DELTA_RENAMED:    code = 'R'; break;
	case GIT_DELTA_COPIED:     code = 'C'; break;
	case GIT_DELTA_IGNORED:    code = 'I'; break;
	case GIT_DELTA_UNTRACKED:  code = '?'; break;
	case GIT_DELTA_UNREADABLE: code = 'X'; break;
	default:                   code = ' '; break;
	}

	return code;
}

static int diff_print_one_name_only(
	const git_diff_delta *delta, float progress, void *data)
{
	diff_print_info *pi = data;
	git_buf *out = pi->buf;

	GIT_UNUSED(progress);

	if ((pi->flags & GIT_DIFF_SHOW_UNMODIFIED) == 0 &&
		delta->status == GIT_DELTA_UNMODIFIED)
		return 0;

	git_buf_clear(out);
	git_buf_puts(out, delta->new_file.path);
	git_buf_putc(out, '\n');
	if (git_buf_oom(out))
		return -1;

	pi->line.origin      = GIT_DIFF_LINE_FILE_HDR;
	pi->line.content     = git_buf_cstr(out);
	pi->line.content_len = git_buf_len(out);

	return pi->print_cb(delta, NULL, &pi->line, pi->payload);
}

static int diff_print_one_name_status(
	const git_diff_delta *delta, float progress, void *data)
{
	diff_print_info *pi = data;
	git_buf *out = pi->buf;
	char old_suffix, new_suffix, code = git_diff_status_char(delta->status);
	int (*strcomp)(const char *, const char *) =
		pi->diff ? pi->diff->strcomp : git__strcmp;

	GIT_UNUSED(progress);

	if ((pi->flags & GIT_DIFF_SHOW_UNMODIFIED) == 0 && code == ' ')
		return 0;

	old_suffix = diff_pick_suffix(delta->old_file.mode);
	new_suffix = diff_pick_suffix(delta->new_file.mode);

	git_buf_clear(out);

	if (delta->old_file.path != delta->new_file.path &&
		strcomp(delta->old_file.path,delta->new_file.path) != 0)
		git_buf_printf(out, "%c\t%s%c %s%c\n", code,
			delta->old_file.path, old_suffix, delta->new_file.path, new_suffix);
	else if (delta->old_file.mode != delta->new_file.mode &&
		delta->old_file.mode != 0 && delta->new_file.mode != 0)
		git_buf_printf(out, "%c\t%s%c %s%c\n", code,
			delta->old_file.path, old_suffix, delta->new_file.path, new_suffix);
	else if (old_suffix != ' ')
		git_buf_printf(out, "%c\t%s%c\n", code, delta->old_file.path, old_suffix);
	else
		git_buf_printf(out, "%c\t%s\n", code, delta->old_file.path);
	if (git_buf_oom(out))
		return -1;

	pi->line.origin      = GIT_DIFF_LINE_FILE_HDR;
	pi->line.content     = git_buf_cstr(out);
	pi->line.content_len = git_buf_len(out);

	return pi->print_cb(delta, NULL, &pi->line, pi->payload);
}

static int diff_print_one_raw(
	const git_diff_delta *delta, float progress, void *data)
{
	diff_print_info *pi = data;
	git_buf *out = pi->buf;
	char code = git_diff_status_char(delta->status);
	char start_oid[GIT_OID_HEXSZ+1], end_oid[GIT_OID_HEXSZ+1];

	GIT_UNUSED(progress);

	if ((pi->flags & GIT_DIFF_SHOW_UNMODIFIED) == 0 && code == ' ')
		return 0;

	git_buf_clear(out);

	git_oid_tostr(start_oid, pi->oid_strlen, &delta->old_file.id);
	git_oid_tostr(end_oid, pi->oid_strlen, &delta->new_file.id);

	git_buf_printf(
		out, (pi->oid_strlen <= GIT_OID_HEXSZ) ?
			":%06o %06o %s... %s... %c" : ":%06o %06o %s %s %c",
		delta->old_file.mode, delta->new_file.mode, start_oid, end_oid, code);

	if (delta->similarity > 0)
		git_buf_printf(out, "%03u", delta->similarity);

	if (delta->old_file.path != delta->new_file.path)
		git_buf_printf(
			out, "\t%s %s\n", delta->old_file.path, delta->new_file.path);
	else
		git_buf_printf(
			out, "\t%s\n", delta->old_file.path ?
			delta->old_file.path : delta->new_file.path);

	if (git_buf_oom(out))
		return -1;

	pi->line.origin      = GIT_DIFF_LINE_FILE_HDR;
	pi->line.content     = git_buf_cstr(out);
	pi->line.content_len = git_buf_len(out);

	return pi->print_cb(delta, NULL, &pi->line, pi->payload);
}

static int diff_print_oid_range(
	git_buf *out, const git_diff_delta *delta, int oid_strlen)
{
	char start_oid[GIT_OID_HEXSZ+1], end_oid[GIT_OID_HEXSZ+1];

	git_oid_tostr(start_oid, oid_strlen, &delta->old_file.id);
	git_oid_tostr(end_oid, oid_strlen, &delta->new_file.id);

	/* TODO: Match git diff more closely */
	if (delta->old_file.mode == delta->new_file.mode) {
		git_buf_printf(out, "index %s..%s %o\n",
			start_oid, end_oid, delta->old_file.mode);
	} else {
		if (delta->old_file.mode == 0) {
			git_buf_printf(out, "new file mode %o\n", delta->new_file.mode);
		} else if (delta->new_file.mode == 0) {
			git_buf_printf(out, "deleted file mode %o\n", delta->old_file.mode);
		} else {
			git_buf_printf(out, "old mode %o\n", delta->old_file.mode);
			git_buf_printf(out, "new mode %o\n", delta->new_file.mode);
		}
		git_buf_printf(out, "index %s..%s\n", start_oid, end_oid);
	}

	return git_buf_oom(out) ? -1 : 0;
}

static int diff_delta_format_with_paths(
	git_buf *out,
	const git_diff_delta *delta,
	const char *oldpfx,
	const char *newpfx,
	const char *template)
{
	const char *oldpath = delta->old_file.path;
	const char *newpath = delta->new_file.path;

	if (git_oid_iszero(&delta->old_file.id)) {
		oldpfx = "";
		oldpath = "/dev/null";
	}
	if (git_oid_iszero(&delta->new_file.id)) {
		newpfx = "";
		newpath = "/dev/null";
	}

	return git_buf_printf(out, template, oldpfx, oldpath, newpfx, newpath);
}

int git_diff_delta__format_file_header(
	git_buf *out,
	const git_diff_delta *delta,
	const char *oldpfx,
	const char *newpfx,
	int oid_strlen)
{
	if (!oldpfx)
		oldpfx = DIFF_OLD_PREFIX_DEFAULT;
	if (!newpfx)
		newpfx = DIFF_NEW_PREFIX_DEFAULT;
	if (!oid_strlen)
		oid_strlen = GIT_ABBREV_DEFAULT + 1;

	git_buf_clear(out);

	git_buf_printf(out, "diff --git %s%s %s%s\n",
		oldpfx, delta->old_file.path, newpfx, delta->new_file.path);

	GITERR_CHECK_ERROR(diff_print_oid_range(out, delta, oid_strlen));

	if ((delta->flags & GIT_DIFF_FLAG_BINARY) == 0)
		diff_delta_format_with_paths(
			out, delta, oldpfx, newpfx, "--- %s%s\n+++ %s%s\n");

	return git_buf_oom(out) ? -1 : 0;
}

static int print_binary_hunk(diff_print_info *pi, git_blob *old, git_blob *new)
{
	git_buf deflate = GIT_BUF_INIT, delta = GIT_BUF_INIT, *out = NULL;
	const void *old_data, *new_data;
	git_off_t old_data_len, new_data_len;
	unsigned long delta_data_len, inflated_len;
	const char *out_type = "literal";
	char *scan, *end;
	int error;

	old_data = old ? git_blob_rawcontent(old) : NULL;
	new_data = new ? git_blob_rawcontent(new) : NULL;

	old_data_len = old ? git_blob_rawsize(old) : 0;
	new_data_len = new ? git_blob_rawsize(new) : 0;

	/* The git_delta function accepts unsigned long only */
	if (!git__is_ulong(old_data_len) || !git__is_ulong(new_data_len))
		return GIT_EBUFS;

	out = &deflate;
	inflated_len = (unsigned long)new_data_len;

	if ((error = git_zstream_deflatebuf(
			out, new_data, (size_t)new_data_len)) < 0)
		goto done;

	/* The git_delta function accepts unsigned long only */
	if (!git__is_ulong((git_off_t)deflate.size)) {
		error = GIT_EBUFS;
		goto done;
	}

	if (old && new) {
		void *delta_data = git_delta(
			old_data, (unsigned long)old_data_len,
			new_data, (unsigned long)new_data_len,
			&delta_data_len, (unsigned long)deflate.size);

		if (delta_data) {
			error = git_zstream_deflatebuf(
				&delta, delta_data, (size_t)delta_data_len);

			git__free(delta_data);

			if (error < 0)
				goto done;

			if (delta.size < deflate.size) {
				out = δ
				out_type = "delta";
				inflated_len = delta_data_len;
			}
		}
	}

	git_buf_printf(pi->buf, "%s %lu\n", out_type, inflated_len);
	pi->line.num_lines++;

	for (scan = out->ptr, end = out->ptr + out->size; scan < end; ) {
		size_t chunk_len = end - scan;
		if (chunk_len > 52)
			chunk_len = 52;

		if (chunk_len <= 26)
			git_buf_putc(pi->buf, (char)chunk_len + 'A' - 1);
		else
			git_buf_putc(pi->buf, (char)chunk_len - 26 + 'a' - 1);

		git_buf_encode_base85(pi->buf, scan, chunk_len);
		git_buf_putc(pi->buf, '\n');

		if (git_buf_oom(pi->buf)) {
			error = -1;
			goto done;
		}

		scan += chunk_len;
		pi->line.num_lines++;
	}

done:
	git_buf_free(&deflate);
	git_buf_free(&delta);

	return error;
}

/* git diff --binary 8d7523f~2 8d7523f~1 */
static int diff_print_patch_file_binary(
	diff_print_info *pi, const git_diff_delta *delta,
	const char *oldpfx, const char *newpfx)
{
	git_blob *old = NULL, *new = NULL;
	const git_oid *old_id, *new_id;
	int error;
	size_t pre_binary_size;

	if ((pi->flags & GIT_DIFF_SHOW_BINARY) == 0)
		goto noshow;

	pre_binary_size = pi->buf->size;
	git_buf_printf(pi->buf, "GIT binary patch\n");
	pi->line.num_lines++;

	old_id = (delta->status != GIT_DELTA_ADDED) ? &delta->old_file.id : NULL;
	new_id = (delta->status != GIT_DELTA_DELETED) ? &delta->new_file.id : NULL;

	if (old_id && (error = git_blob_lookup(&old, pi->diff->repo, old_id)) < 0)
		goto done;
	if (new_id && (error = git_blob_lookup(&new, pi->diff->repo,new_id)) < 0)
		goto done;

	if ((error = print_binary_hunk(pi, old, new)) < 0 ||
		(error = git_buf_putc(pi->buf, '\n')) < 0 ||
		(error = print_binary_hunk(pi, new, old)) < 0)
	{
		if (error == GIT_EBUFS) {
			giterr_clear();
			git_buf_truncate(pi->buf, pre_binary_size);
			goto noshow;
		}
	}

	pi->line.num_lines++;

done:
	git_blob_free(old);
	git_blob_free(new);

	return error;

noshow:
	pi->line.num_lines = 1;
	return diff_delta_format_with_paths(
		pi->buf, delta, oldpfx, newpfx,
		"Binary files %s%s and %s%s differ\n");
}

static int diff_print_patch_file(
	const git_diff_delta *delta, float progress, void *data)
{
	int error;
	diff_print_info *pi = data;
	const char *oldpfx =
		pi->diff ? pi->diff->opts.old_prefix : DIFF_OLD_PREFIX_DEFAULT;
	const char *newpfx =
		pi->diff ? pi->diff->opts.new_prefix : DIFF_NEW_PREFIX_DEFAULT;

	bool binary = !!(delta->flags & GIT_DIFF_FLAG_BINARY);
	bool show_binary = !!(pi->flags & GIT_DIFF_SHOW_BINARY);
	int oid_strlen = binary && show_binary ?
		GIT_OID_HEXSZ + 1 : pi->oid_strlen;

	GIT_UNUSED(progress);

	if (S_ISDIR(delta->new_file.mode) ||
		delta->status == GIT_DELTA_UNMODIFIED ||
		delta->status == GIT_DELTA_IGNORED ||
		delta->status == GIT_DELTA_UNREADABLE ||
		(delta->status == GIT_DELTA_UNTRACKED &&
		 (pi->flags & GIT_DIFF_SHOW_UNTRACKED_CONTENT) == 0))
		return 0;

	if ((error = git_diff_delta__format_file_header(
			pi->buf, delta, oldpfx, newpfx, oid_strlen)) < 0)
		return error;

	pi->line.origin      = GIT_DIFF_LINE_FILE_HDR;
	pi->line.content     = git_buf_cstr(pi->buf);
	pi->line.content_len = git_buf_len(pi->buf);

	if ((error = pi->print_cb(delta, NULL, &pi->line, pi->payload)) != 0)
		return error;

	if (!binary)
		return 0;

	git_buf_clear(pi->buf);

	if ((error = diff_print_patch_file_binary(pi, delta, oldpfx, newpfx)) < 0)
		return error;

	pi->line.origin      = GIT_DIFF_LINE_BINARY;
	pi->line.content     = git_buf_cstr(pi->buf);
	pi->line.content_len = git_buf_len(pi->buf);

	return pi->print_cb(delta, NULL, &pi->line, pi->payload);
}

static int diff_print_patch_hunk(
	const git_diff_delta *d,
	const git_diff_hunk *h,
	void *data)
{
	diff_print_info *pi = data;

	if (S_ISDIR(d->new_file.mode))
		return 0;

	pi->line.origin      = GIT_DIFF_LINE_HUNK_HDR;
	pi->line.content     = h->header;
	pi->line.content_len = h->header_len;

	return pi->print_cb(d, h, &pi->line, pi->payload);
}

static int diff_print_patch_line(
	const git_diff_delta *delta,
	const git_diff_hunk *hunk,
	const git_diff_line *line,
	void *data)
{
	diff_print_info *pi = data;

	if (S_ISDIR(delta->new_file.mode))
		return 0;

	return pi->print_cb(delta, hunk, line, pi->payload);
}

/* print a git_diff to an output callback */
int git_diff_print(
	git_diff *diff,
	git_diff_format_t format,
	git_diff_line_cb print_cb,
	void *payload)
{
	int error;
	git_buf buf = GIT_BUF_INIT;
	diff_print_info pi;
	git_diff_file_cb print_file = NULL;
	git_diff_hunk_cb print_hunk = NULL;
	git_diff_line_cb print_line = NULL;

	switch (format) {
	case GIT_DIFF_FORMAT_PATCH:
		print_file = diff_print_patch_file;
		print_hunk = diff_print_patch_hunk;
		print_line = diff_print_patch_line;
		break;
	case GIT_DIFF_FORMAT_PATCH_HEADER:
		print_file = diff_print_patch_file;
		break;
	case GIT_DIFF_FORMAT_RAW:
		print_file = diff_print_one_raw;
		break;
	case GIT_DIFF_FORMAT_NAME_ONLY:
		print_file = diff_print_one_name_only;
		break;
	case GIT_DIFF_FORMAT_NAME_STATUS:
		print_file = diff_print_one_name_status;
		break;
	default:
		giterr_set(GITERR_INVALID, "Unknown diff output format (%d)", format);
		return -1;
	}

	if (!(error = diff_print_info_init(
			&pi, &buf, diff, format, print_cb, payload)))
	{
		error = git_diff_foreach(
			diff, print_file, print_hunk, print_line, &pi);

		if (error) /* make sure error message is set */
			giterr_set_after_callback_function(error, "git_diff_print");
	}

	git_buf_free(&buf);

	return error;
}

/* print a git_patch to an output callback */
int git_patch_print(
	git_patch *patch,
	git_diff_line_cb print_cb,
	void *payload)
{
	int error;
	git_buf temp = GIT_BUF_INIT;
	diff_print_info pi;

	assert(patch && print_cb);

	if (!(error = diff_print_info_init(
			&pi, &temp, git_patch__diff(patch),
			GIT_DIFF_FORMAT_PATCH, print_cb, payload)))
	{
		error = git_patch__invoke_callbacks(
			patch, diff_print_patch_file, diff_print_patch_hunk,
			diff_print_patch_line, &pi);

		if (error) /* make sure error message is set */
			giterr_set_after_callback_function(error, "git_patch_print");
	}

	git_buf_free(&temp);

	return error;
}

int git_diff_print_callback__to_buf(
	const git_diff_delta *delta,
	const git_diff_hunk *hunk,
	const git_diff_line *line,
	void *payload)
{
	git_buf *output = payload;
	GIT_UNUSED(delta); GIT_UNUSED(hunk);

	if (!output) {
		giterr_set(GITERR_INVALID, "Buffer pointer must be provided");
		return -1;
	}

	if (line->origin == GIT_DIFF_LINE_ADDITION ||
		line->origin == GIT_DIFF_LINE_DELETION ||
		line->origin == GIT_DIFF_LINE_CONTEXT)
		git_buf_putc(output, line->origin);

	return git_buf_put(output, line->content, line->content_len);
}

int git_diff_print_callback__to_file_handle(
	const git_diff_delta *delta,
	const git_diff_hunk *hunk,
	const git_diff_line *line,
	void *payload)
{
	FILE *fp = payload ? payload : stdout;

	GIT_UNUSED(delta); GIT_UNUSED(hunk);

	if (line->origin == GIT_DIFF_LINE_CONTEXT ||
		line->origin == GIT_DIFF_LINE_ADDITION ||
		line->origin == GIT_DIFF_LINE_DELETION)
		fputc(line->origin, fp);
	fwrite(line->content, 1, line->content_len, fp);
	return 0;
}

/* print a git_patch to a git_buf */
int git_patch_to_buf(git_buf *out, git_patch *patch)
{
	assert(out && patch);
	git_buf_sanitize(out);
	return git_patch_print(patch, git_diff_print_callback__to_buf, out);
}


text:
package com.shirtsio.model;

public class WebHookAddResponse {
    private WebHookAdd result;

    public WebHookAdd getResult() {
        return result;
    }

    public void setResult(WebHookAdd result) {
        this.result = result;
    }
}


text:
/* Convenience routines for working with seek tables */

/* This .h cannot be included by itself; #include "share/grabbag.h" instead. */

#ifndef GRABAG__SEEKTABLE_H
#define GRABAG__SEEKTABLE_H

#include "FLAC/format.h"

#ifdef __cplusplus
extern "C" {
#endif

FLAC__bool grabbag__seektable_convert_specification_to_template(const char *spec, FLAC__bool only_explicit_placeholders, FLAC__uint64 total_samples_to_encode, unsigned sample_rate, FLAC__StreamMetadata *seektable_template, FLAC__bool *spec_has_real_points);

#ifdef __cplusplus
}
#endif

#endif


text:
require 'spec_helper'

describe Munson::Middleware::JsonParser, type: :response do
  let(:document){ response_body(:albums_include_artist) }

  let(:middleware) {
    described_class.new(lambda {|env|
      Faraday::Response.new(env)
    })
  }

  def faraday_env(body)
    env = {
      :body => body, :request => {},
      :request_headers => Faraday::Utils::Headers.new({}),
      :response_headers => Faraday::Utils::Headers.new({})
    }
    env[:response_headers]['content-type'] = 'application/vnd.api+json'
    env
  end

  context 'when the body is present' do
    it 'parses the body as JSON' do
      env = faraday_env(document)
      body = middleware.call(env).env.body

      expect(body).to match JSON.parse(document, symbolize_names: true)
    end
  end

  context 'when the body is empty' do
    it 'returns an empty hash' do
      env = faraday_env('')
      body = middleware.call(env).env.body
      expect(body).to eq({})
    end
  end
end


text:
package quiz.application;

import java.util.ArrayList;
import java.util.List;

public class Quiz {

	private int nQues = 10;
	private List<Question> questions;

	public Quiz()
	{
		questions = new ArrayList<Question>();
	}

	public Quiz(int n)
	{
		this.nQues = n;
		questions = new ArrayList<Question>();
	}

	public void add(Question q)
	{
		if(this.questions.size() < nQues)
			this.questions.add(q);
	}

	public Question getIndex(int index)
	{
		return this.questions.get(index);
	}

	public int length()
	{
		return this.questions.size();
	}

	public void clear()
	{
		this.questions.clear();
	}

	public int getnQues() {
		return nQues;
	}

	public void setnQues(int nQues) {
		this.nQues = nQues;
	}

}


text:
require 'spec_helper'

describe Org::Namespaces::TagsController do
  let(:organization) { create(:organization)}
  let(:namespace) { create(:tag_namespace, organization: organization)}
  let(:tag) { create(:tag, name: 'foo', namespace: namespace, organization: organization) }
  let(:charge) { create(:charge, tag: tag, organization: organization) }
  let(:user) { create(:confirmed_user, organization: organization)}

  before(:each) do
    allow(controller).to receive(:current_organization).and_return( organization )
    sign_in user
  end

  it 'should get index' do
    get :index, params: { namespace_id: namespace, organization_id: organization }
    expect(response).to be_success
    expect(assigns(:tags)).to include(tag)
  end
end


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Generic;

using Internal.Runtime;
using Internal.Text;
using Internal.TypeSystem;

namespace ILCompiler.DependencyAnalysis
{
    public class ReadyToRunHeaderNode : ObjectNode, ISymbolDefinitionNode
    {
        struct HeaderItem
        {
            public HeaderItem(ReadyToRunSectionType id, ObjectNode node, ISymbolNode startSymbol, ISymbolNode endSymbol)
            {
                Id = id;
                Node = node;
                StartSymbol = startSymbol;
                EndSymbol = endSymbol;
            }

            readonly public ReadyToRunSectionType Id;
            readonly public ObjectNode Node;
            readonly public ISymbolNode StartSymbol;
            readonly public ISymbolNode EndSymbol;
        }

        List<HeaderItem> _items = new List<HeaderItem>();
        TargetDetails _target;

        public ReadyToRunHeaderNode(TargetDetails target)
        {
            _target = target;
        }

        public void Add(ReadyToRunSectionType id, ObjectNode node, ISymbolNode startSymbol, ISymbolNode endSymbol = null)
        {
            _items.Add(new HeaderItem(id, node, startSymbol, endSymbol));
        }

        public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb)
        {
            sb.Append(nameMangler.CompilationUnitPrefix);
            sb.Append("__ReadyToRunHeader");
        }
        public int Offset => 0;
        public override bool IsShareable => false;

        protected override string GetName(NodeFactory factory) => this.GetMangledName(factory.NameMangler);

        public override bool StaticDependenciesAreComputed => true;

        public override ObjectNodeSection Section
        {
            get
            {
                if (_target.IsWindows)
                    return ObjectNodeSection.ReadOnlyDataSection;
                else
                    return ObjectNodeSection.DataSection;
            }
        }

        public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false)
        {
            ObjectDataBuilder builder = new ObjectDataBuilder(factory, relocsOnly);
            builder.RequireInitialPointerAlignment();
            builder.AddSymbol(this);

            // Don't bother sorting if we're not emitting the contents
            if (!relocsOnly)
                _items.Sort((x, y) => Comparer<int>.Default.Compare((int)x.Id, (int)y.Id));

            // ReadyToRunHeader.Magic
            builder.EmitInt((int)(ReadyToRunHeaderConstants.Signature));

            // ReadyToRunHeader.MajorVersion
            builder.EmitShort((short)(ReadyToRunHeaderConstants.CurrentMajorVersion));
            builder.EmitShort((short)(ReadyToRunHeaderConstants.CurrentMinorVersion));

            // ReadyToRunHeader.Flags
            builder.EmitInt(0);

            // ReadyToRunHeader.NumberOfSections
            var sectionCountReservation = builder.ReserveShort();

            // ReadyToRunHeader.EntrySize
            builder.EmitByte((byte)(8 + 2 * factory.Target.PointerSize));

            // ReadyToRunHeader.EntryType
            builder.EmitByte(1);

            int count = 0;
            foreach (var item in _items)
            {
                // Skip empty entries
                if (!relocsOnly && item.Node.ShouldSkipEmittingObjectNode(factory))
                    continue;

                builder.EmitInt((int)item.Id);

                ModuleInfoFlags flags = 0;
                if (item.EndSymbol != null)
                {
                    flags |= ModuleInfoFlags.HasEndPointer;
                }
                builder.EmitInt((int)flags);

                builder.EmitPointerReloc(item.StartSymbol);

                if (item.EndSymbol != null)
                {
                    builder.EmitPointerReloc(item.EndSymbol);
                }
                else
                {
                    builder.EmitZeroPointer();
                }

                count++;
            }
            builder.EmitShort(sectionCountReservation, checked((short)count));

            return builder.ToObjectData();
        }
    }
}


text:
package gov.va.escreening.controller.dashboard;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping(value = "/dashboard")
public class UserListViewController {

    @SuppressWarnings("unused")
    private static final Logger logger = LoggerFactory.getLogger(UserListViewController.class);

    /**
     * Initialize and setup page.
     * @param model
     * @return
     */
    @RequestMapping(value = "/userListView", method = RequestMethod.GET)
    public String setUpPageListView(Model model) {

        return "adminTab/userListView";
    }
}


text:
export declare class CommentTag {
    tagName: string;
    paramName: string;
    text: string;
    constructor(tagName: string, paramName?: string, text?: string);
    toObject(): any;
}


text: watchify .\public\js\storify\storify.cowabunga.js -o .\public\js\storify\dist\cowabunga.bundle.js


text:
[![Build Status](https://secure.travis-ci.org/cmanzana/node-publish.png)](http://travis-ci.org/cmanzana/node-publish)

npm module to automate publishing of npm modules
Useful when you want to publish every time you bump the version in your module as part of your continuos integration setup.

When running publish in your module:
- if your module is not yet in the registry then publish will do nothing (you need to publish manually the first version of your module)
- if your module has the same version, or lower version than the version in the registry then publish will do nothing
- if your module has bigger version than the version in the registry then publish will perform a ['npm publish'](http://npmjs.org/doc/publish.html) of your module

## Installation

npm install publish

## Usage

The most common way of using publish is to have it as a posttest script in your package.json:

    "scripts": {
      "test": "tap test/*.js", // tap as an example
      "posttest": "publish"
    }

which means that on successful test run, publish will try to 'npm publish' your module.

Notice that your CI machine needs to be configured with an npm user (http://npmjs.org/doc/adduser.html) that is
authorized to publish the package.

The options that you can use with publish are:

* --on-major  Publishes on major version changes.
* --on-minor  Publishes on minor version changes.
* --on-patch  Publishes on patch version changes.
* --on-build  Publishes on build version changes.
* --version   Print the version of publish.
* --help      Print the help of publish.

### Examples

    publish --on-major --on-minor

will only publish when the local major or minor versions are higher than the remote ones

    publish --on-build

will only publish when the local build version is higher than the remote one

    publish

will only publish when the local version is higher than the remote one

## License
[MIT](https://github.com/cmanzana/node-publish/blob/master/MIT-LICENSE)


text:
import {createRequire} from 'module';
import url from 'url';
import path from 'path';

/**
 * Commonjs equivalent of `require.resolve`.
 * @param {string} packageName
 */
function resolveModulePath(packageName) {
  const require = createRequire(import.meta.url);
  return require.resolve(packageName);
}

/**
 * @param {ImportMeta} importMeta
 */
function getModulePath(importMeta) {
  return url.fileURLToPath(importMeta.url);
}

/**
 * @param {ImportMeta} importMeta
 */
function getModuleDirectory(importMeta) {
  return path.dirname(getModulePath(importMeta));
}

export {
  resolveModulePath,
  getModulePath,
  getModuleDirectory,
};


text:
Glyphicons
----------
Shortcut directives for Bootstrap's glyphicons.

_For the list of all available icons, see http://getbootstrap.com/components/#glyphicons-glyphs_

###Simple glyph icon (span) `<glyph>`
#####Attributes:
  - `icon`: the variable part of the Bootstrap 3.x glyphicons classes (i.e without the 'glyphicon-' prefix).

  _See [here](http://getbootstrap.com/components/#glyphicons-glyphs) for the full list._

#####Example:
```html
<!-- Heart icon -->
<glyph icon="heart"></glyph>
```

###Button glyphicon `<btn-glyph>`
#####Attributes:
  - `icon`: the variable part of the Bootstrap 3.x glyphicons classes (i.e without the 'glyphicon-' prefix).
  _See [here](http://getbootstrap.com/components/#glyphicons-glyphs) for the full list._

  - `theme`: the variable part of the Bootstrap 3.x buttons theme classes (i.e without the 'btn-' prefix).

    The stock ones are as follows _(but you can create your own in your stylesheet if you want using the `btn-` prefix)_:
   * `primary`
   * `success`
   * `info`
   * `warning`
   * `danger`

  _**Note**: If no `theme` attribute is specified, Angustrap will default-back to Bootstrap's `.btn-default` class_

  - `size`: the variable part of the Bootstrap 3.x buttons size classes (i.e without the 'btn-' prefix).
   Possible choices are:
     * `lg`
     * `sm`
     * `xs`

#####Example:
```html
<!-- A large orange button with a heart in it -->
<btn-glyph icon="heart" theme="warning" size="lg"></glyph>
```

-------------

Dropdown `<dropdown>`
---------
A single directive to abstract all of
Bootstrap's [dropdown](http://getbootstrap.com/components/#dropdowns) components.
> One Directive to rule them all,

> One Directive to find them,

> One Directive to bring them all and in the darkness 2-way data-bind them,

> In the Land of Mordor where the Shadow-DOM lie

####Examples:

#####Single-button dropdown
```html
<dropdown as-type="btn" theme="danger" size="lg" icon="heart" title="Dropdown">
    <dropdown-item as-href="http://google.com">Google</dropdown-item>
    <dropdown-item as-href="http://twitter.com">Twitter</dropdown-item>
</dropdown>

<!-- Drop up -->
<dropdown as-type="btn" theme="success" size="sm" icon="qrcode"  dropup="true" title="Dropup">
    <dropdown-item as-href="http://google.com">Google</dropdown-item>
    <dropdown-item as-href="http://twitter.com">Twitter</dropdown-item>
</dropdown>
```

#####Split-button dropdown
```html
<dropdown as-type="split" theme="danger" size="lg" icon="heart" title="Sign-In">
    <dropdown-item as-href="http://google.com">Google</dropdown-item>
    <dropdown-item as-href="http://twitter.com">Twitter</dropdown-item>
</dropdown>

<!-- Drop up -->
<dropdown as-type="split" theme="info" size="xs" icon="qrcode" title="Sign-In" dropup="true">
    <dropdown-item as-href="http://google.com">Google</dropdown-item>
    <dropdown-item as-href="http://twitter.com">Twitter</dropdown-item>
</dropdown>
```

####Attributes:
  * `as-type`: the type of the dropdown. can be either `btn` or `split`

  * `theme`: the variable part of the Bootstrap 3.x buttons theme classes (i.e without the 'btn-' prefix).
    The stock ones are as follows _(but you can create your own in your stylesheet using the `btn-` prefix)_:
    * `primary`
    * `success`
    * `info`
    * `warning`
    * `danger`

  * `icon`: the variable part of the Bootstrap 3.x glyphicons classes (i.e without the 'glyphicon-' prefix).
    See [here](http://getbootstrap.com/components/#glyphicons-glyphs) for the full list.

  * `size`: the variable part of the Bootstrap 3.x buttons size classes (i.e without the 'btn-' prefix).
    Possible choice are:
      * `lg`
      * `sm`
      * `xs`

  * `title`: The string to display inside the action button of the split dropdown

  * `dropup`: (_Boolean_) If set to true, the dropdown will effectively drop _up_ and the caret direction will be inverted.
  If set to false or not specified, the element will drop _down_

=======

###List Item `<list-item>`
This is the `<list-item>` directive used through transclusion by the dropdown & navbar directives.

#####Attributes:
  - `asHref`: the url this dropdown-item should point to
_Note that you can still pass the usual `.disabled` class to disable an item

=======

###List Divider `<list-divider>`
The `<list-divider>` directive used through transclusion by the dropdown & navbar directives

-------------

Navigation Bar
==============

Bootstrap's navigation bar in just 1 line of markup (without the content).

####Example:
```html
<navbar as-id="navbar" fixed="top" title="Angustrap" title-href="#">
    <navbar-list side="right">
        <list-item as-href="#">Item 1</list-item>
        <list-item as-href="#">Item 2</list-item>
        <list-item as-href="#">Item 3</list-item>
        <navbar-dropdown title="Sign-In">
            <list-item as-href="#">Dropdown item 1</list-item>
            <list-item as-href="#">Dropdown item 2</list-item>
        </navbar-dropdown>
    </navbar-list>
</navbar>
```

Navbar `<navbar>`
-----------------

#### Attributes:
 * `theme`: Can be either `default` or `inverse`. If none is specified, Angustrap will fallback to `default`.

 * `title`: The navigation bar title, usually your brand name.

 * `titleHref`: The URL the navbar `title` link should point to.

 * `fixed`: Whether the navbar should be fixed to the `top` or `bottom` of the page.
    If this attribute is not specified or set to `static`, the navbar will be at the top of the screen and scroll with the content (`.navbar-static-top`).

 * `center`: Whether the navbar content & title should be centered (i.e: inside a `div.container`)

NavbarList `<navbar-list>`
-----------------

#### Attributes:
* `side`: Whether the list should be aligned to the `left` or to the `right` inside its `<navbar>` parent.

NavbarDropdown `<navbar-dropdown>`
-----------------

#### Attributes:
* `title`: The title of the dropdown list item. Has the same appearance as a `<list-item>`

-------------

Input Groups
============

InputGroup `<input-group>`
--------------------------
A single directive to abstract all of Bootstrap's input-group components.

####Examples:
```html
<!-- Left-aligned large <span> add-on with text input -->
<input-group title="@" as-type="span" size="lg" side="left" type="text"></input-group>

<!-- Right-aligned blue <button> add-on with email input -->
<input-group title="@" as-type="btn" side="right" type="email" theme="primary"></input-group>
```

####Attributes:
* `title`: The text to display inside of the input add-on (span, button... depending on the `type` attribute)

* `as-type`: The type of the add-on. Can be on of the following:
  * `span`: Will result in a `<span>` add-on
  * `btn`: Will result in a `<button>` add-on

* `type`: The HTML5 `type` attribute of the `<input>` ("text", "tel", "number", "email", etc...)

* `side`: Whether the add-on should be on the `left` or on the `right` of the `<input>`

* `size`: Defines the size of the input-group. Accepted values are:
  * `lg`
  * `sm`
  If none is specified, the medium size will be used.

* `theme`: _Only valid for button input-groups (`<input-group type="btn">`)._

    The variable part of the Bootstrap 3.x buttons theme classes (i.e without the 'btn-' prefix).

    The stock ones are as follows _(but you can create your own in your stylesheet using the `btn-` prefix)_:
    * `primary`
    * `success`
    * `info`
    * `warning`
    * `danger`

    _**Note**: If no `theme` attribute is specified, Angustrap will default-back to Bootstrap's `.btn-default` class_

Panels
============

Panel `<panel>`
--------------------------
A directive to abstract Bootstrap's panel component.

####Examples:
```html
<!-- Default panel -->
<panel title="My Panel">
    ...
</panel>

<!-- Themed panel -->
<panel title="My Panel" theme="primary">
    ...
</panel>

<!-- Panel with footer -->
<panel title="My Panel" theme="primary" footer>
    ...
</panel>
```

####Attributes:
* `title`: The text to display inside of the input add-on (span, button... depending on the `type` attribute)

* `theme`: The variable part of the Bootstrap 3.x buttons theme classes (i.e without the 'btn-' prefix).

    The stock ones are as follows _(but you can create your own in your stylesheet using the `btn-` prefix)_:
    * `primary`
    * `success`
    * `info`
    * `warning`
    * `danger`

    _**Note**: If no `theme` attribute is specified, Angustrap will default-back to Bootstrap's `default` theme_

* `footer`: _(Boolean)_ Whether the panel title should be placed at the bottom of the panel or not

Alerts
============

Alert `<alert>`
--------------------------
A directive to abstract Bootstrap's alert component.

####Examples:
```html
<!-- Red alert -->
<alert theme="danger">Something ain't right!</alert>

<!-- Green alert -->
<alert theme="success">Props! You did it!</alert>

<!-- Dismissible blue alert -->
<alert theme="info" dismissible>Props! You did it!</alert>
```

####Attributes:
* `theme`: The variable part of the Bootstrap 3.x buttons theme classes (i.e without the 'btn-' prefix).

    The stock ones are as follows _(but you can create your own in your stylesheet using the `btn-` prefix)_:
    * `primary`
    * `success`
    * `info`
    * `warning`
    * `danger`

* `dismissible`: Whether the alert should be dismissible via a close button at its top-right corner

  _**Note:** when using links inside an `<alert>`, remember to use the `.alert-link` class to provide matching colors on the link. ([example](http://getbootstrap.com/components/#alerts-links))_

Progress Bars
============

ProgressBar `<progress-bar>`
--------------------------
A directive to abstract Bootstrap's progress bar component.

####Examples:
```html
<!-- Green Progress Bar -->
<progress-bar theme="success" current="95"></progress-bar>

<!-- Red Progress Bar with label -->
<progress-bar theme="danger" title="Angustrap" current="75"></progress-bar>

<!-- Orange Striped Progress Bar with label -->
<progress-bar theme="warning" current="75" striped></progress-bar>

<!-- Blue Animated Progress Bar with label -->
<progress-bar theme="warning" title="Angustrap" current="75" striped animated></progress-bar>
```

####Attributes:
* `theme`: The variable part of the Bootstrap 3.x buttons theme classes (i.e without the 'btn-' prefix).

    The stock ones are as follows _(but you can create your own in your stylesheet using the `btn-` prefix)_:
    * `primary`
    * `success`
    * `info`
    * `warning`
    * `danger`

    _**Note**: If no `theme` attribute is specified, Angustrap will default-back to Bootstrap's `default` theme_

* `current`: _(Integer)_ the current progress percentage

* `title`: _(String)_ the label to display inside the progressbar (optional)

* `striped`: _(Boolean)_ whether the progress-bar should be striped or not

* `animated`: _(Boolean)_ if the progress bar is `striped`, defined whether the progress-bar stripes should be animated

Labels
============

AsLabel `<as-label>`
--------------------------
A shortcut directive for Bootstrap's label component.

####Examples:
```html
<!-- Default label -->
<as-label>My Label</as-label>

<!-- Green label -->
<as-label theme="success">Success Label</as-label>

<!-- Blue label -->
<as-label theme="info">Info Label</as-label>
```

####Attributes:
* `theme`: The variable part of the Bootstrap 3.x buttons theme classes (i.e without the 'btn-' prefix).

    The stock ones are as follows _(but you can create your own in your stylesheet using the `btn-` prefix)_:
    * `primary`
    * `success`
    * `info`
    * `warning`
    * `danger`

Wells
============

Well `<well>`
--------------------------
A shortcut directive for Bootstrap's well component.

####Examples:
```html
<!-- Large well -->
<well size="lg">Large Well</as-label>

<!-- Default well -->
<well>Default Well</well>

<!-- Small well -->
<well size="sm">Small Well</well>
```

####Attributes:
* `theme`: The variable part of the Bootstrap 3.x buttons theme classes (i.e without the 'btn-' prefix).

    The stock ones are as follows _(but you can create your own in your stylesheet using the `btn-` prefix)_:
    * `primary`
    * `success`
    * `info`
    * `warning`
    * `danger`


text:
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module

# Cache of actual callables.
_standard_context_processors = None
# We need the CSRF processor no matter what the user has in their settings,
# because otherwise it is a security vulnerability, and we can't afford to leave
# this to human error or failure to read migration instructions.
_builtin_context_processors =  ('django.core.context_processors.csrf',)

class ContextPopException(Exception):
    "pop() has been called more times than push()"
    pass

class BaseContext(object):
    def __init__(self, dict_=None):
        dict_ = dict_ or {}
        self.dicts = [dict_]

    def __repr__(self):
        return repr(self.dicts)

    def __iter__(self):
        for d in reversed(self.dicts):
            yield d

    def push(self):
        d = {}
        self.dicts.append(d)
        return d

    def pop(self):
        if len(self.dicts) == 1:
            raise ContextPopException
        return self.dicts.pop()

    def __setitem__(self, key, value):
        "Set a variable in the current context"
        self.dicts[-1][key] = value

    def __getitem__(self, key):
        "Get a variable's value, starting at the current context and going upward"
        for d in reversed(self.dicts):
            if key in d:
                return d[key]
        raise KeyError(key)

    def __delitem__(self, key):
        "Delete a variable from the current context"
        del self.dicts[-1][key]

    def has_key(self, key):
        for d in self.dicts:
            if key in d:
                return True
        return False

    def __contains__(self, key):
        return self.has_key(key)

    def get(self, key, otherwise=None):
        for d in reversed(self.dicts):
            if key in d:
                return d[key]
        return otherwise

class Context(BaseContext):
    "A stack container for variable context"
    def __init__(self, dict_=None, autoescape=True, current_app=None, use_l10n=None):
        self.autoescape = autoescape
        self.use_l10n = use_l10n
        self.current_app = current_app
        self.render_context = RenderContext()
        super(Context, self).__init__(dict_)

    def update(self, other_dict):
        "Pushes other_dict to the stack of dictionaries in the Context"
        if not hasattr(other_dict, '__getitem__'):
            raise TypeError('other_dict must be a mapping (dictionary-like) object.')
        self.dicts.append(other_dict)
        return other_dict

class RenderContext(BaseContext):
    """
    A stack container for storing Template state.

    RenderContext simplifies the implementation of template Nodes by providing a
    safe place to store state between invocations of a node's `render` method.

    The RenderContext also provides scoping rules that are more sensible for
    'template local' variables. The render context stack is pushed before each
    template is rendered, creating a fresh scope with nothing in it. Name
    resolution fails if a variable is not found at the top of the RequestContext
    stack. Thus, variables are local to a specific template and don't affect the
    rendering of other templates as they would if they were stored in the normal
    template context.
    """
    def __iter__(self):
        for d in self.dicts[-1]:
            yield d

    def has_key(self, key):
        return key in self.dicts[-1]

    def get(self, key, otherwise=None):
        d = self.dicts[-1]
        if key in d:
            return d[key]
        return otherwise

# This is a function rather than module-level procedural code because we only
# want it to execute if somebody uses RequestContext.
def get_standard_processors():
    from django.conf import settings
    global _standard_context_processors
    if _standard_context_processors is None:
        processors = []
        collect = []
        collect.extend(_builtin_context_processors)
        collect.extend(settings.TEMPLATE_CONTEXT_PROCESSORS)
        for path in collect:
            i = path.rfind('.')
            module, attr = path[:i], path[i+1:]
            try:
                mod = import_module(module)
            except ImportError, e:
                raise ImproperlyConfigured('Error importing request processor module %s: "%s"' % (module, e))
            try:
                func = getattr(mod, attr)
            except AttributeError:
                raise ImproperlyConfigured('Module "%s" does not define a "%s" callable request processor' % (module, attr))
            processors.append(func)
        _standard_context_processors = tuple(processors)
    return _standard_context_processors

class RequestContext(Context):
    """
    This subclass of template.Context automatically populates itself using
    the processors defined in TEMPLATE_CONTEXT_PROCESSORS.
    Additional processors can be specified as a list of callables
    using the "processors" keyword argument.
    """
    def __init__(self, request, dict=None, processors=None, current_app=None, use_l10n=None):
        Context.__init__(self, dict, current_app=current_app, use_l10n=use_l10n)
        if processors is None:
            processors = ()
        else:
            processors = tuple(processors)
        for processor in get_standard_processors() + processors:
            self.update(processor(request))


text:
package com.android.common.ide.common.blame;

import com.google.common.base.Optional;
import com.google.common.collect.BiMap;
import com.google.common.collect.EnumHashBiMap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Maps;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;

import java.io.File;
import java.io.IOException;

/**
 * Class to handle json serialization and deserialization of messages.
 *
 * Reads json objects of the form:
 *
 *

 * {
 *     "kind":"ERROR",
 *     "text":"errorText",
 *     "original":"unparsed error text: Error in some intermediate file",
 *     "sources": [{
 *         "file":"/path/to/source.java",
 *         "position":{
 *             "startLine":1,
 *             "startColumn":2,
 *             "startOffset":3,
 *             "endLine":4,
 *             "endColumn":5,
 *             "endOffset":6
 *         }
 *     }]
 * }

 *
 * All fields, other than text, may be omitted. They have the following defaults:
 *
 *

 *
Property	        Default	             Notes

 *
kind (ERROR, WARNING,
 *             INFO, UNKNOWN)	  UNKNOWN

 *
text	            Empty String	 Should not be omitted.

 *
file (Absolute)	 {} [unknown]	 See {@link SourceFileJsonTypeAdapter}

 *
position	        UNKNOWN

 *
startLine,
 *             startColumn,
 *             startOffset	     -1 [unknown]	 0-based

 *
endLine,
 *             endColumn,
 *             endOffset	       startLine, startColumn,
 *                                      startOffset

 *

 *
 * Notes
 *

 *
Offset need not be included, if needed by the consumer of the message it can
 *         be derived from the file, line and column.

 *
If line is included and column is not the message will be considered to apply
 *         to the whole line.

 *
A message can have multiple sources.

 *

 * It also can read legacy serialized objects of the form:
 *
 *
{
 *     "kind":"ERROR",
 *     "text":"errorText",
 *     "sourcePath": "/path/to/source.java",
 *     "position":{
 *         "startLine":1,
 *         "startColumn":2,
 *         "startOffset":3,
 *         "endLine":4,
 *         "endColumn":5,
 *         "endOffset":6
 *     }
 * }

 *
 * These serializers are implemented using the lower-level TypeAdapter gson API which gives much
 * more control and allow changes to be made without breaking backward compatibility.
 */
public class MessageJsonSerializer extends TypeAdapter<Message> {

    private static final String KIND = "kind";

    private static final String TEXT = "text";

    private static final String SOURCE_FILE_POSITIONS = "sources";

    private static final String RAW_MESSAGE = "original";

    private static final String TOOL_NAME = "tool";

    private static final String LEGACY_SOURCE_PATH = "sourcePath";

    private static final String LEGACY_POSITION = "position";

    private static final BiMap<Message.Kind, String> KIND_STRING_ENUM_MAP;

    static {
        EnumHashBiMap<Message.Kind, String> map = EnumHashBiMap.create(Message.Kind.class);
        map.put(Message.Kind.ERROR, "error");
        map.put(Message.Kind.WARNING, "warning");
        map.put(Message.Kind.INFO, "info");
        map.put(Message.Kind.STATISTICS, "statistics");
        map.put(Message.Kind.UNKNOWN, "unknown");
        map.put(Message.Kind.SIMPLE, "simple");
        KIND_STRING_ENUM_MAP = Maps.unmodifiableBiMap(map);
    }

    private final SourceFilePositionJsonSerializer mSourceFilePositionTypeAdapter;
    private final SourcePositionJsonTypeAdapter mSourcePositionTypeAdapter;

    public MessageJsonSerializer() {
        mSourceFilePositionTypeAdapter = new SourceFilePositionJsonSerializer();
        mSourcePositionTypeAdapter = mSourceFilePositionTypeAdapter.getSourcePositionTypeAdapter();
    }

    @Override
    public void write(JsonWriter out, Message message) throws IOException {
        out.beginObject()
                .name(KIND).value(KIND_STRING_ENUM_MAP.get(message.getKind()))
                .name(TEXT).value(message.getText())
                .name(SOURCE_FILE_POSITIONS).beginArray();
        for (SourceFilePosition position : message.getSourceFilePositions()) {
            mSourceFilePositionTypeAdapter.write(out, position);
        }
        out.endArray();
        if (!message.getRawMessage().equals(message.getText())) {
            out.name(RAW_MESSAGE).value(message.getRawMessage());
        }
        if (message.getToolName().isPresent()) {
            out.name(TOOL_NAME).value(message.getToolName().get());
        }
        out.endObject();
    }

    @Override
    public Message read(JsonReader in) throws IOException {
        in.beginObject();
        Message.Kind kind = Message.Kind.UNKNOWN;
        String text = "";
        String rawMessage = null;
        Optional<String> toolName = Optional.absent();
        ImmutableList.Builder<SourceFilePosition> positions =
                new ImmutableList.Builder<SourceFilePosition>();
        SourceFile legacyFile = SourceFile.UNKNOWN;
        SourcePosition legacyPosition = SourcePosition.UNKNOWN;
        while (in.hasNext()) {
            String name = in.nextName();
            if (name.equals(KIND)) {
                //noinspection StringToUpperCaseOrToLowerCaseWithoutLocale
                Message.Kind theKind = KIND_STRING_ENUM_MAP.inverse()
                        .get(in.nextString().toLowerCase());
                kind = (theKind != null) ? theKind : Message.Kind.UNKNOWN;
            } else if (name.equals(TEXT)) {
                text = in.nextString();
            } else if (name.equals(RAW_MESSAGE)) {
                rawMessage = in.nextString();
            } else if (name.equals(TOOL_NAME)) {
                toolName = Optional.of(in.nextString());
            } else if (name.equals(SOURCE_FILE_POSITIONS)) {
                switch (in.peek()) {
                    case BEGIN_ARRAY:
                        in.beginArray();
                        while(in.hasNext()) {
                            positions.add(mSourceFilePositionTypeAdapter.read(in));
                        }
                        in.endArray();
                        break;
                    case BEGIN_OBJECT:
                        positions.add(mSourceFilePositionTypeAdapter.read(in));
                        break;
                    default:
                        in.skipValue();
                        break;
                }
            } else if (name.equals(LEGACY_SOURCE_PATH)) {
                legacyFile = new SourceFile(new File(in.nextString()));
            } else if (name.equals(LEGACY_POSITION)) {
                legacyPosition = mSourcePositionTypeAdapter.read(in);
            } else {
                in.skipValue();
            }
        }
        in.endObject();

        if (legacyFile != SourceFile.UNKNOWN || legacyPosition != SourcePosition.UNKNOWN) {
            positions.add(new SourceFilePosition(legacyFile, legacyPosition));
        }
        if (rawMessage == null) {
            rawMessage = text;
        }
        ImmutableList<SourceFilePosition> sourceFilePositions = positions.build();
        if (!sourceFilePositions.isEmpty()) {
            return new Message(kind, text, rawMessage, toolName, sourceFilePositions);
        } else {
            return new Message(kind, text, rawMessage, toolName, ImmutableList.of(SourceFilePosition.UNKNOWN));
        }
    }

    public static void registerTypeAdapters(GsonBuilder builder) {
        builder.registerTypeAdapter(SourceFile.class, new SourceFileJsonTypeAdapter());
        builder.registerTypeAdapter(SourcePosition.class, new SourcePositionJsonTypeAdapter());
        builder.registerTypeAdapter(SourceFilePosition.class,
                new SourceFilePositionJsonSerializer());
        builder.registerTypeAdapter(Message.class, new MessageJsonSerializer());
    }
}


text:
package org.jcodec.codecs.h264.decode;

import org.jcodec.codecs.h264.H264Utils;
import org.jcodec.codecs.h264.io.model.SliceHeader;
import org.jcodec.common.model.ColorSpace;

/**
 * This class is part of JCodec ( www.jcodec.org ) This software is distributed
 * under FreeBSD License
 *
 * Current state of the decoder, this data is accessed from many methods
 *
 * @author The JCodec project
 *
 */
public class DecoderState {
    public int[] chromaQpOffset;
    public int qp;
    public byte[][] leftRow;
    public byte[][] topLine;
    public byte[][] topLeft;

    ColorSpace chromaFormat;

    H264Utils.MvList mvTop;
    H264Utils.MvList mvLeft;
    H264Utils.MvList mvTopLeft;

    public DecoderState(SliceHeader sh) {
        int mbWidth = sh.sps.picWidthInMbsMinus1 + 1;
        chromaQpOffset = new int[] { sh.pps.chromaQpIndexOffset,
                sh.pps.extended != null ? sh.pps.extended.secondChromaQpIndexOffset : sh.pps.chromaQpIndexOffset };

        chromaFormat = sh.sps.chromaFormatIdc;

        mvTop = new H264Utils.MvList((mbWidth << 2) + 1);
        mvLeft = new H264Utils.MvList(4);
        mvTopLeft = new H264Utils.MvList(1);

        leftRow = new byte[3][16];
        topLeft = new byte[3][4];
        topLine = new byte[3][mbWidth << 4];

        qp = sh.pps.picInitQpMinus26 + 26 + sh.sliceQpDelta;
    }
}