text:
package monitor

import (
	"bufio"
	"bytes"
	"encoding/binary"
	"encoding/json"
	"fmt"
	"net"
	"os"
	"unsafe"

	"github.com/cilium/cilium/pkg/byteorder"
	"github.com/cilium/cilium/pkg/identity"
	"github.com/cilium/cilium/pkg/monitor/api"
	"github.com/cilium/cilium/pkg/types"
)

const (
	// traceNotifyCommonLen is the minimum length required to determine the version of the TN event.
	traceNotifyCommonLen = 16
	// traceNotifyV0Len is the amount of packet data provided in a trace notification v0.
	traceNotifyV0Len = 32
	// traceNotifyV1Len is the amount of packet data provided in a trace notification v1.
	traceNotifyV1Len = 48
	// TraceReasonEncryptMask is the bit used to indicate encryption or not
	TraceReasonEncryptMask uint8 = 0x80
)

const (
	// TraceNotifyFlagIsIPv6 is set in TraceNotify.Flags when the
	// notification refers to an IPv6 flow
	TraceNotifyFlagIsIPv6 uint8 = 1
)

const (
	TraceNotifyVersion0 = iota
	TraceNotifyVersion1
)

// TraceNotifyV0 is the common message format for versions 0 and 1.
type TraceNotifyV0 struct {
	Type     uint8
	ObsPoint uint8
	Source   uint16
	Hash     uint32
	OrigLen  uint32
	CapLen   uint16
	Version  uint16
	SrcLabel identity.NumericIdentity
	DstLabel identity.NumericIdentity
	DstID    uint16
	Reason   uint8
	Flags    uint8
	Ifindex  uint32
	// data
}

// TraceNotifyV1 is the version 1 message format.
type TraceNotifyV1 struct {
	TraceNotifyV0
	OrigIP types.IPv6
	// data
}

// TraceNotify is the message format of a trace notification in the BPF ring buffer
type TraceNotify TraceNotifyV1

var (
	traceNotifyLength = map[uint16]uint{
		TraceNotifyVersion0: traceNotifyV0Len,
		TraceNotifyVersion1: traceNotifyV1Len,
	}
)

// Reasons for forwarding a packet.
const (
	TraceReasonPolicy = iota
	TraceReasonCtEstablished
	TraceReasonCtReply
	TraceReasonCtRelated
	TraceReasonCtReopened
)

var traceReasons = map[uint8]string{
	TraceReasonPolicy:        "new",
	TraceReasonCtEstablished: "established",
	TraceReasonCtReply:       "reply",
	TraceReasonCtRelated:     "related",
	TraceReasonCtReopened:    "reopened",
}

func connState(reason uint8) string {
	r := reason & ^TraceReasonEncryptMask
	if str, ok := traceReasons[r]; ok {
		return str
	}
	return fmt.Sprintf("%d", reason)
}

func fetchVersion(data []byte, tn *TraceNotify) (version uint16, err error) {
	offset := unsafe.Offsetof(tn.Version)
	length := unsafe.Sizeof(tn.Version)
	reader := bytes.NewReader(data[offset : offset+length])
	err = binary.Read(reader, byteorder.Native, &version)
	return version, err
}

// DecodeTraceNotify will decode 'data' into the provided TraceNotify structure
func DecodeTraceNotify(data []byte, tn *TraceNotify) error {
	if len(data) < traceNotifyCommonLen {
		return fmt.Errorf("Unknown trace event")
	}

	version, err := fetchVersion(data, tn)
	if err != nil {
		return err
	}
	switch version {
	case TraceNotifyVersion0:
		err = binary.Read(bytes.NewReader(data), byteorder.Native, &tn.TraceNotifyV0)
	case TraceNotifyVersion1:
		err = binary.Read(bytes.NewReader(data), byteorder.Native, tn)
	default:
		err = fmt.Errorf("Unrecognized trace event (version %d)", version)
	}
	return err
}

// dumpIdentity dumps the source and destination identities in numeric or
// human-readable format.
func (n *TraceNotify) dumpIdentity(buf *bufio.Writer, numeric DisplayFormat) {
	if numeric {
		fmt.Fprintf(buf, "identity %d->%d", n.SrcLabel, n.DstLabel)
	} else {
		fmt.Fprintf(buf, "identity %s->%s", n.SrcLabel, n.DstLabel)
	}
}

func (n *TraceNotify) encryptReason() string {
	if (n.Reason & TraceReasonEncryptMask) != 0 {
		return "encrypted "
	}
	return ""
}

func (n *TraceNotify) traceReason() string {
	return connState(n.Reason)
}

func (n *TraceNotify) traceSummary() string {
	switch n.ObsPoint {
	case api.TraceToLxc:
		return fmt.Sprintf("-> endpoint %d", n.DstID)
	case api.TraceToProxy:
		return "-> proxy"
	case api.TraceToHost:
		return "-> host from"
	case api.TraceToStack:
		return "-> stack"
	case api.TraceToOverlay:
		return "-> overlay"
	case api.TraceToNetwork:
		return "-> network"
	case api.TraceFromLxc:
		return fmt.Sprintf("<- endpoint %d", n.Source)
	case api.TraceFromProxy:
		return "<- proxy"
	case api.TraceFromHost:
		return "<- host"
	case api.TraceFromStack:
		return "<- stack"
	case api.TraceFromOverlay:
		return "<- overlay"
	case api.TraceFromNetwork:
		return "<- network"
	default:
		return "unknown trace"
	}
}

// OriginalIP returns the original source IP if reverse NAT was performed on
// the flow
func (n *TraceNotify) OriginalIP() net.IP {
	if (n.Flags & TraceNotifyFlagIsIPv6) != 0 {
		return n.OrigIP[:]
	}
	return n.OrigIP[:4]
}

// DataOffset returns the offset from the beginning of TraceNotify where the
// trace notify data begins.
//
// Returns zero for invalid or unknown TraceNotify messages.
func (n *TraceNotify) DataOffset() uint {
	return traceNotifyLength[n.Version]
}

// DumpInfo prints a summary of the trace messages.
func (n *TraceNotify) DumpInfo(data []byte, numeric DisplayFormat) {
	buf := bufio.NewWriter(os.Stdout)
	hdrLen := n.DataOffset()
	if n.encryptReason() != "" {
		fmt.Fprintf(buf, "%s %s flow %#x ",
			n.traceSummary(), n.encryptReason(), n.Hash)
	} else {
		fmt.Fprintf(buf, "%s flow %#x ", n.traceSummary(), n.Hash)
	}
	n.dumpIdentity(buf, numeric)
	fmt.Fprintf(buf, " state %s ifindex %s orig-ip %s: %s\n", n.traceReason(),
		ifname(int(n.Ifindex)), n.OriginalIP().String(), GetConnectionSummary(data[hdrLen:]))
	buf.Flush()
}

// DumpVerbose prints the trace notification in human readable form
func (n *TraceNotify) DumpVerbose(dissect bool, data []byte, prefix string, numeric DisplayFormat) {
	buf := bufio.NewWriter(os.Stdout)
	fmt.Fprintf(buf, "%s MARK %#x FROM %d %s: %d bytes (%d captured), state %s",
		prefix, n.Hash, n.Source, api.TraceObservationPoint(n.ObsPoint), n.OrigLen, n.CapLen, connState(n.Reason))

	if n.Ifindex != 0 {
		fmt.Fprintf(buf, ", interface %s", ifname(int(n.Ifindex)))
	}

	if n.SrcLabel != 0 || n.DstLabel != 0 {
		n.dumpIdentity(buf, numeric)
	}

	fmt.Fprintf(buf, ", orig-ip %s", n.OriginalIP().String())

	if n.DstID != 0 {
		fmt.Fprintf(buf, ", to endpoint %d\n", n.DstID)
	} else {
		fmt.Fprintf(buf, "\n")
	}

	hdrLen := n.DataOffset()
	if n.CapLen > 0 && len(data) > int(hdrLen) {
		Dissect(dissect, data[hdrLen:])
	}
	buf.Flush()
}

func (n *TraceNotify) getJSON(data []byte, cpuPrefix string) (string, error) {
	v := TraceNotifyToVerbose(n)
	v.CPUPrefix = cpuPrefix
	hdrLen := n.DataOffset()
	if n.CapLen > 0 && len(data) > int(hdrLen) {
		v.Summary = GetDissectSummary(data[hdrLen:])
	}

	ret, err := json.Marshal(v)
	return string(ret), err
}

// DumpJSON prints notification in json format
func (n *TraceNotify) DumpJSON(data []byte, cpuPrefix string) {
	resp, err := n.getJSON(data, cpuPrefix)
	if err == nil {
		fmt.Println(resp)
	}
}

// TraceNotifyVerbose represents a json notification printed by monitor
type TraceNotifyVerbose struct {
	CPUPrefix        string `json:"cpu,omitempty"`
	Type             string `json:"type,omitempty"`
	Mark             string `json:"mark,omitempty"`
	Ifindex          string `json:"ifindex,omitempty"`
	State            string `json:"state,omitempty"`
	ObservationPoint string `json:"observationPoint"`
	TraceSummary     string `json:"traceSummary"`

	Source   uint16                   `json:"source"`
	Bytes    uint32                   `json:"bytes"`
	SrcLabel identity.NumericIdentity `json:"srcLabel"`
	DstLabel identity.NumericIdentity `json:"dstLabel"`
	DstID    uint16                   `json:"dstID"`

	Summary *DissectSummary `json:"summary,omitempty"`
}

// TraceNotifyToVerbose creates verbose notification from base TraceNotify
func TraceNotifyToVerbose(n *TraceNotify) TraceNotifyVerbose {
	return TraceNotifyVerbose{
		Type:             "trace",
		Mark:             fmt.Sprintf("%#x", n.Hash),
		Ifindex:          ifname(int(n.Ifindex)),
		State:            connState(n.Reason),
		ObservationPoint: api.TraceObservationPoint(n.ObsPoint),
		TraceSummary:     n.traceSummary(),
		Source:           n.Source,
		Bytes:            n.OrigLen,
		SrcLabel:         n.SrcLabel,
		DstLabel:         n.DstLabel,
		DstID:            n.DstID,
	}
}


text:
/*
 * Ory Hydra API
 *
 * Documentation for all of Ory Hydra's APIs.
 *
 * API version: 1.0.0
 * Contact: hi@ory.sh
 */

// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT.

package client

import (
	"bytes"
	"context"
	"io/ioutil"
	"net/http"
	"net/url"
)

// Linger please
var (
	_ context.Context
)

type MetadataApi interface {

	/*
			 * GetVersion Return Running Software Version.
			 * This endpoint returns the version of Ory Hydra.

		If the service supports TLS Edge Termination, this endpoint does not require the
		`X-Forwarded-Proto` header to be set.

		Be aware that if you are running multiple nodes of this service, the version will never
		refer to the cluster state, only to a single instance.
			 * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
			 * @return MetadataApiApiGetVersionRequest
	*/
	GetVersion(ctx context.Context) MetadataApiApiGetVersionRequest

	/*
	 * GetVersionExecute executes the request
	 * @return InlineResponse2001
	 */
	GetVersionExecute(r MetadataApiApiGetVersionRequest) (*InlineResponse2001, *http.Response, error)

	/*
			 * IsAlive Check HTTP Server Status
			 * This endpoint returns a HTTP 200 status code when Ory Hydra is accepting incoming
		HTTP requests. This status does currently not include checks whether the database connection is working.

		If the service supports TLS Edge Termination, this endpoint does not require the
		`X-Forwarded-Proto` header to be set.

		Be aware that if you are running multiple nodes of this service, the health status will never
		refer to the cluster state, only to a single instance.
			 * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
			 * @return MetadataApiApiIsAliveRequest
	*/
	IsAlive(ctx context.Context) MetadataApiApiIsAliveRequest

	/*
	 * IsAliveExecute executes the request
	 * @return HealthStatus
	 */
	IsAliveExecute(r MetadataApiApiIsAliveRequest) (*HealthStatus, *http.Response, error)

	/*
			 * IsReady Check HTTP Server and Database Status
			 * This endpoint returns a HTTP 200 status code when Ory Hydra is up running and the environment dependencies (e.g.
		the database) are responsive as well.

		If the service supports TLS Edge Termination, this endpoint does not require the
		`X-Forwarded-Proto` header to be set.

		Be aware that if you are running multiple nodes of Ory Hydra, the health status will never
		refer to the cluster state, only to a single instance.
			 * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
			 * @return MetadataApiApiIsReadyRequest
	*/
	IsReady(ctx context.Context) MetadataApiApiIsReadyRequest

	/*
	 * IsReadyExecute executes the request
	 * @return InlineResponse200
	 */
	IsReadyExecute(r MetadataApiApiIsReadyRequest) (*InlineResponse200, *http.Response, error)
}

// MetadataApiService MetadataApi service
type MetadataApiService service

type MetadataApiApiGetVersionRequest struct {
	ctx        context.Context
	ApiService MetadataApi
}

func (r MetadataApiApiGetVersionRequest) Execute() (*InlineResponse2001, *http.Response, error) {
	return r.ApiService.GetVersionExecute(r)
}

/*
 * GetVersion Return Running Software Version.
 * This endpoint returns the version of Ory Hydra.

If the service supports TLS Edge Termination, this endpoint does not require the
`X-Forwarded-Proto` header to be set.

Be aware that if you are running multiple nodes of this service, the version will never
refer to the cluster state, only to a single instance.
 * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
 * @return MetadataApiApiGetVersionRequest
*/
func (a *MetadataApiService) GetVersion(ctx context.Context) MetadataApiApiGetVersionRequest {
	return MetadataApiApiGetVersionRequest{
		ApiService: a,
		ctx:        ctx,
	}
}

/*
 * Execute executes the request
 * @return InlineResponse2001
 */
func (a *MetadataApiService) GetVersionExecute(r MetadataApiApiGetVersionRequest) (*InlineResponse2001, *http.Response, error) {
	var (
		localVarHTTPMethod   = http.MethodGet
		localVarPostBody     interface{}
		localVarFormFileName string
		localVarFileName     string
		localVarFileBytes    []byte
		localVarReturnValue  *InlineResponse2001
	)

	localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "MetadataApiService.GetVersion")
	if err != nil {
		return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()}
	}

	localVarPath := localBasePath + "/version"

	localVarHeaderParams := make(map[string]string)
	localVarQueryParams := url.Values{}
	localVarFormParams := url.Values{}

	// to determine the Content-Type header
	localVarHTTPContentTypes := []string{}

	// set Content-Type header
	localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
	if localVarHTTPContentType != "" {
		localVarHeaderParams["Content-Type"] = localVarHTTPContentType
	}

	// to determine the Accept header
	localVarHTTPHeaderAccepts := []string{"application/json"}

	// set Accept header
	localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
	if localVarHTTPHeaderAccept != "" {
		localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
	}
	req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
	if err != nil {
		return localVarReturnValue, nil, err
	}

	localVarHTTPResponse, err := a.client.callAPI(req)
	if err != nil || localVarHTTPResponse == nil {
		return localVarReturnValue, localVarHTTPResponse, err
	}

	localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body)
	localVarHTTPResponse.Body.Close()
	localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody))
	if err != nil {
		return localVarReturnValue, localVarHTTPResponse, err
	}

	if localVarHTTPResponse.StatusCode >= 300 {
		newErr := &GenericOpenAPIError{
			body:  localVarBody,
			error: localVarHTTPResponse.Status,
		}
		return localVarReturnValue, localVarHTTPResponse, newErr
	}

	err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
	if err != nil {
		newErr := &GenericOpenAPIError{
			body:  localVarBody,
			error: err.Error(),
		}
		return localVarReturnValue, localVarHTTPResponse, newErr
	}

	return localVarReturnValue, localVarHTTPResponse, nil
}

type MetadataApiApiIsAliveRequest struct {
	ctx        context.Context
	ApiService MetadataApi
}

func (r MetadataApiApiIsAliveRequest) Execute() (*HealthStatus, *http.Response, error) {
	return r.ApiService.IsAliveExecute(r)
}

/*
 * IsAlive Check HTTP Server Status
 * This endpoint returns a HTTP 200 status code when Ory Hydra is accepting incoming
HTTP requests. This status does currently not include checks whether the database connection is working.

If the service supports TLS Edge Termination, this endpoint does not require the
`X-Forwarded-Proto` header to be set.

Be aware that if you are running multiple nodes of this service, the health status will never
refer to the cluster state, only to a single instance.
 * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
 * @return MetadataApiApiIsAliveRequest
*/
func (a *MetadataApiService) IsAlive(ctx context.Context) MetadataApiApiIsAliveRequest {
	return MetadataApiApiIsAliveRequest{
		ApiService: a,
		ctx:        ctx,
	}
}

/*
 * Execute executes the request
 * @return HealthStatus
 */
func (a *MetadataApiService) IsAliveExecute(r MetadataApiApiIsAliveRequest) (*HealthStatus, *http.Response, error) {
	var (
		localVarHTTPMethod   = http.MethodGet
		localVarPostBody     interface{}
		localVarFormFileName string
		localVarFileName     string
		localVarFileBytes    []byte
		localVarReturnValue  *HealthStatus
	)

	localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "MetadataApiService.IsAlive")
	if err != nil {
		return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()}
	}

	localVarPath := localBasePath + "/health/alive"

	localVarHeaderParams := make(map[string]string)
	localVarQueryParams := url.Values{}
	localVarFormParams := url.Values{}

	// to determine the Content-Type header
	localVarHTTPContentTypes := []string{}

	// set Content-Type header
	localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
	if localVarHTTPContentType != "" {
		localVarHeaderParams["Content-Type"] = localVarHTTPContentType
	}

	// to determine the Accept header
	localVarHTTPHeaderAccepts := []string{"application/json"}

	// set Accept header
	localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
	if localVarHTTPHeaderAccept != "" {
		localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
	}
	req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
	if err != nil {
		return localVarReturnValue, nil, err
	}

	localVarHTTPResponse, err := a.client.callAPI(req)
	if err != nil || localVarHTTPResponse == nil {
		return localVarReturnValue, localVarHTTPResponse, err
	}

	localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body)
	localVarHTTPResponse.Body.Close()
	localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody))
	if err != nil {
		return localVarReturnValue, localVarHTTPResponse, err
	}

	if localVarHTTPResponse.StatusCode >= 300 {
		newErr := &GenericOpenAPIError{
			body:  localVarBody,
			error: localVarHTTPResponse.Status,
		}
		if localVarHTTPResponse.StatusCode == 500 {
			var v GenericError
			err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
			if err != nil {
				newErr.error = err.Error()
				return localVarReturnValue, localVarHTTPResponse, newErr
			}
			newErr.model = v
		}
		return localVarReturnValue, localVarHTTPResponse, newErr
	}

	err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
	if err != nil {
		newErr := &GenericOpenAPIError{
			body:  localVarBody,
			error: err.Error(),
		}
		return localVarReturnValue, localVarHTTPResponse, newErr
	}

	return localVarReturnValue, localVarHTTPResponse, nil
}

type MetadataApiApiIsReadyRequest struct {
	ctx        context.Context
	ApiService MetadataApi
}

func (r MetadataApiApiIsReadyRequest) Execute() (*InlineResponse200, *http.Response, error) {
	return r.ApiService.IsReadyExecute(r)
}

/*
 * IsReady Check HTTP Server and Database Status
 * This endpoint returns a HTTP 200 status code when Ory Hydra is up running and the environment dependencies (e.g.
the database) are responsive as well.

If the service supports TLS Edge Termination, this endpoint does not require the
`X-Forwarded-Proto` header to be set.

Be aware that if you are running multiple nodes of Ory Hydra, the health status will never
refer to the cluster state, only to a single instance.
 * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
 * @return MetadataApiApiIsReadyRequest
*/
func (a *MetadataApiService) IsReady(ctx context.Context) MetadataApiApiIsReadyRequest {
	return MetadataApiApiIsReadyRequest{
		ApiService: a,
		ctx:        ctx,
	}
}

/*
 * Execute executes the request
 * @return InlineResponse200
 */
func (a *MetadataApiService) IsReadyExecute(r MetadataApiApiIsReadyRequest) (*InlineResponse200, *http.Response, error) {
	var (
		localVarHTTPMethod   = http.MethodGet
		localVarPostBody     interface{}
		localVarFormFileName string
		localVarFileName     string
		localVarFileBytes    []byte
		localVarReturnValue  *InlineResponse200
	)

	localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "MetadataApiService.IsReady")
	if err != nil {
		return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()}
	}

	localVarPath := localBasePath + "/health/ready"

	localVarHeaderParams := make(map[string]string)
	localVarQueryParams := url.Values{}
	localVarFormParams := url.Values{}

	// to determine the Content-Type header
	localVarHTTPContentTypes := []string{}

	// set Content-Type header
	localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
	if localVarHTTPContentType != "" {
		localVarHeaderParams["Content-Type"] = localVarHTTPContentType
	}

	// to determine the Accept header
	localVarHTTPHeaderAccepts := []string{"application/json"}

	// set Accept header
	localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
	if localVarHTTPHeaderAccept != "" {
		localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
	}
	req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
	if err != nil {
		return localVarReturnValue, nil, err
	}

	localVarHTTPResponse, err := a.client.callAPI(req)
	if err != nil || localVarHTTPResponse == nil {
		return localVarReturnValue, localVarHTTPResponse, err
	}

	localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body)
	localVarHTTPResponse.Body.Close()
	localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody))
	if err != nil {
		return localVarReturnValue, localVarHTTPResponse, err
	}

	if localVarHTTPResponse.StatusCode >= 300 {
		newErr := &GenericOpenAPIError{
			body:  localVarBody,
			error: localVarHTTPResponse.Status,
		}
		if localVarHTTPResponse.StatusCode == 503 {
			var v InlineResponse503
			err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
			if err != nil {
				newErr.error = err.Error()
				return localVarReturnValue, localVarHTTPResponse, newErr
			}
			newErr.model = v
		}
		return localVarReturnValue, localVarHTTPResponse, newErr
	}

	err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
	if err != nil {
		newErr := &GenericOpenAPIError{
			body:  localVarBody,
			error: err.Error(),
		}
		return localVarReturnValue, localVarHTTPResponse, newErr
	}

	return localVarReturnValue, localVarHTTPResponse, nil
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Bregananta\Blockchain;

use Illuminate\Support\Facades\Facade;

class BlockchainFacade extends Facade {

    protected static function getFacadeAccessor()
    {
        return 'blockchain';
    }

}


text:
<component name="ProjectRunConfigurationManager">
  <configuration default="false" name="Playground" type="Application" factoryName="Application">
    <option name="MAIN_CLASS_NAME" value="org.jetbrains.dokka.MainKt" />
    <module name="fatjar_main" />
    <option name="PROGRAM_PARAMETERS" value="-module playground test -format html -output out/html" />
    <option name="WORKING_DIRECTORY" value="file://$PROJECT_DIR$" />
    <method />
  </configuration>
</component>


text:
//
//  ZZOperation.h
//  aaa
//
//  Created by 张凯 on 15/11/23.
//  Copyright © 2015年 sablib. All rights reserved.
//

#import <Foundation/Foundation.h>

/**
 *  state1 & state2 如果不为0即能够转换
 */
//typedef NS_ENUM(NSInteger, ZZOperationState) {
//    ZZOperationStateInitialized = 1,
//    ZZOperationStatePending = 7,
//    ZZOperationStateEvaluatingConditions = 6,
//    ZZOperationStateReady = 12,
//    ZZOperationStateExecuting = 24,
//    ZZOperationStateFinishing = 56,
//    ZZOperationStateFinished = 96
//};

@protocol ZZOperationCondition;
@protocol ZZOperationObserver;

@interface ZZOperation : NSOperation

@property (nonatomic, readonly) NSArray<id<ZZOperationCondition>> *conditions;

- (void)willEnqueue;
- (void)execute;
- (void)finish;
- (void)finishWithErrors:(NSArray<NSError *> *)errors;
- (void)cancelWithError:(NSError *)error;

- (void)addCondition:(id<ZZOperationCondition>)condition;
- (void)addObserver:(id<ZZOperationObserver>)observer;
- (void)addDependency:(NSOperation *)op;

- (void)produceOperation:(NSOperation *)operation;

@end


text:
package com.mentor.nucleus.bp.compare.contentmergeviewer;

import java.util.List;
import java.util.Vector;

import org.eclipse.compare.IStreamContentAccessor;
import org.eclipse.compare.contentmergeviewer.IDocumentRange;
import org.eclipse.compare.contentmergeviewer.TextMergeViewer;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;

import com.mentor.nucleus.bp.compare.ComparePlugin;
import com.mentor.nucleus.bp.compare.ModelCacheManager;
import com.mentor.nucleus.bp.compare.ModelCacheManager.ModelLoadException;
import com.mentor.nucleus.bp.core.CorePlugin;

public class ModelContentViewer extends Viewer {

	private ModelCacheManager modelManager = ComparePlugin.getDefault().getModelCacheManager();

	private SourceViewer fSourceViewer;
	private List inputs = new Vector();
	Object input;

	ModelContentViewer(Composite parent) {
		fSourceViewer = new SourceViewer(parent, null, SWT.H_SCROLL + SWT.V_SCROLL);
		Control control = fSourceViewer.getTextWidget();
		Font font = JFaceResources.getFont(TextMergeViewer.class.getName());
		control.setFont(font);
		control.addDisposeListener(new DisposeListener() {
			public void widgetDisposed(DisposeEvent e) {
				handleDispose();
			}
		});
		fSourceViewer.setEditable(false);
	}

	public Control getControl() {
		return fSourceViewer.getTextWidget();
	}

	public void setInput(Object aInput) {
		if (aInput != null) {
			inputs.add(aInput);

			input = aInput;
			try {
				IStreamContentAccessor modelText = modelManager.getModel(aInput, this);

				if (modelText instanceof IDocumentRange) {
					fSourceViewer.setDocument(((IDocumentRange) modelText).getDocument());
				}

			} catch (ModelLoadException e) {
				CorePlugin.showImportErrorMessage(false, e.getMessage());
			}
		}
	}

	public Object getInput() {
		return input;
	}

	public ISelection getSelection() {
		return fSourceViewer.getSelection();
	}

	public void setSelection(ISelection s, boolean reveal) {
		fSourceViewer.setSelection(s, reveal);
	}

	public void refresh() {
		fSourceViewer.refresh();
	}

	protected void handleDispose() {
		for (int i = 0; i < inputs.size(); i++) {
			modelManager.releaseModel(inputs.get(i), this);
		}
		inputs.clear();
	}

}


text:
package java.text;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamField;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Currency;
import java.util.Locale;

/**
 * A concrete subclass of {@link NumberFormat} that formats decimal numbers. It
 * has a variety of features designed to make it possible to parse and format
 * numbers in any locale, including support for Western, Arabic, or Indic
 * digits. It also supports different flavors of numbers, including integers
 * ("123"), fixed-point numbers ("123.4"), scientific notation ("1.23E4"),
 * percentages ("12%"), and currency amounts ("$123"). All of these flavors can
 * be easily localized.
 *

 * This is an enhanced version of {@code DecimalFormat} that is based on
 * the standard version in the RI. New or changed functionality is labeled
 * NEW.
 *

 * To obtain a {@link NumberFormat} for a specific locale (including the default
 * locale), call one of {@code NumberFormat}'s factory methods such as
 * {@code NumberFormat.getInstance}. Do not call the {@code DecimalFormat}
 * constructors directly, unless you know what you are doing, since the
 * {@link NumberFormat} factory methods may return subclasses other than
 * {@code DecimalFormat}. If you need to customize the format object, do
 * something like this:

 *
 *

 * NumberFormat f = NumberFormat.getInstance(loc);
 * if (f instanceof DecimalFormat) {
 *     ((DecimalFormat)f).setDecimalSeparatorAlwaysShown(true);
 * }
 *

 *
 *

 *
Example:

 *

 *
 *

 * // Print out a number using the localized number, currency,
 * // and percent format for each locale
 * Locale[] locales = NumberFormat.getAvailableLocales();
 * double myNumber = -1234.56;
 * NumberFormat format;
 * for (int j = 0; j < 3; ++j) {
 *     System.out.println("FORMAT");
 *     for (int i = 0; i < locales.length; ++i) {
 *         if (locales[i].getCountry().length() == 0) {
 *             // Skip language-only locales
 *             continue;
 *         }
 *         System.out.print(locales[i].getDisplayName());
 *         switch (j) {
 *             case 0:
 *                 format = NumberFormat.getInstance(locales[i]);
 *                 break;
 *             case 1:
 *                 format = NumberFormat.getCurrencyInstance(locales[i]);
 *                 break;
 *             default:
 *                 format = NumberFormat.getPercentInstance(locales[i]);
 *                 break;
 *         }
 *         try {
 *             // Assume format is a DecimalFormat
 *             System.out.print(": "; + ((DecimalFormat)format).toPattern() + " -> "
 *                     + form.format(myNumber));
 *         } catch (Exception e) {
 *         }
 *         try {
 *             System.out.println(" -> " + format.parse(form.format(myNumber)));
 *         } catch (ParseException e) {
 *         }
 *     }
 * }
 *

 *
 *

 *
Patterns

 *

 * A {@code DecimalFormat} consists of a pattern and a set of
 * symbols. The pattern may be set directly using
 * {@link #applyPattern(String)}, or indirectly using other API methods which
 * manipulate aspects of the pattern, such as the minimum number of integer
 * digits. The symbols are stored in a {@link DecimalFormatSymbols} object. When
 * using the {@link NumberFormat} factory methods, the pattern and symbols are
 * read from ICU's locale data.
 *
Special Pattern Characters

 *

 * Many characters in a pattern are taken literally; they are matched during
 * parsing and are written out unchanged during formatting. On the other hand,
 * special characters stand for other characters, strings, or classes of
 * characters. For example, the '#' character is replaced by a localized digit.
 * Often the replacement character is the same as the pattern character; in the
 * U.S. locale, the ',' grouping character is replaced by ','. However, the
 * replacement is still happening, and if the symbols are modified, the grouping
 * character changes. Some special characters affect the behavior of the
 * formatter by their presence; for example, if the percent character is seen,
 * then the value is multiplied by 100 before being displayed.
 *

 * To insert a special character in a pattern as a literal, that is, without any
 * special meaning, the character must be quoted. There are some exceptions to
 * this which are noted below.
 *

 * The characters listed here are used in non-localized patterns. Localized
 * patterns use the corresponding characters taken from this formatter's
 * {@link DecimalFormatSymbols} object instead, and these characters lose their
 * special status. Two exceptions are the currency sign and quote, which are not
 * localized.
 *

 *

 * Symbol
 * Location
 * Localized?
 * Meaning
 *

 *

 * {@code 0}
 * Number
 * Yes
 * Digit.
 *

 *

 * {@code @}
 * Number
 * No
 * NEW  Significant
 * digit.
 *

 *

 * {@code #}
 * Number
 * Yes
 * Digit, leading zeroes are not shown.
 *

 *

 * {@code .}
 * Number
 * Yes
 * Decimal separator or monetary decimal separator.
 *

 *

 * {@code -}
 * Number
 * Yes
 * Minus sign.
 *

 *

 * {@code ,}
 * Number
 * Yes
 * Grouping separator.
 *

 *

 * {@code E}
 * Number
 * Yes
 * Separates mantissa and exponent in scientific notation.
 * Does not need to be quoted in prefix or suffix.
 *

 *

 * {@code +}
 * Exponent
 * Yes
 * NEW  Prefix
 * positive exponents with localized plus sign.
 * Does not need to be quoted in prefix or suffix.
 *

 *

 * {@code ;}
 * Subpattern boundary
 * Yes
 * Separates positive and negative subpatterns.
 *

 *

 * {@code %}
 * Prefix or suffix
 * Yes
 * Multiply by 100 and show as percentage.
 *

 *

 * {@code \u2030} ({@code \u2030})
 * Prefix or suffix
 * Yes
 * Multiply by 1000 and show as per mille.
 *

 *

 * {@code ¤} ({@code \u00A4})
 * Prefix or suffix
 * No
 * Currency sign, replaced by currency symbol. If doubled, replaced by
 * international currency symbol. If present in a pattern, the monetary decimal
 * separator is used instead of the decimal separator.
 *

 *

 * {@code '}
 * Prefix or suffix
 * No
 * Used to quote special characters in a prefix or suffix, for example,
 * {@code "'#'#"} formats 123 to {@code "#123"}. To create a single quote
 * itself, use two in a row: {@code "# o''clock"}.
 *

 *

 * {@code *}
 * Prefix or suffix boundary
 * Yes
 * NEW  Pad escape,
 * precedes pad character.
 *

 *

 *

 * A {@code DecimalFormat} pattern contains a postive and negative subpattern,
 * for example, "#,##0.00;(#,##0.00)". Each subpattern has a prefix, a numeric
 * part and a suffix. If there is no explicit negative subpattern, the negative
 * subpattern is the localized minus sign prefixed to the positive subpattern.
 * That is, "0.00" alone is equivalent to "0.00;-0.00". If there is an explicit
 * negative subpattern, it serves only to specify the negative prefix and
 * suffix; the number of digits, minimal digits, and other characteristics are
 * ignored in the negative subpattern. This means that "#,##0.0#;(#)" produces
 * precisely the same result as "#,##0.0#;(#,##0.0#)".
 *

 * The prefixes, suffixes, and various symbols used for infinity, digits,
 * thousands separators, decimal separators, etc. may be set to arbitrary
 * values, and they will appear properly during formatting. However, care must
 * be taken that the symbols and strings do not conflict, or parsing will be
 * unreliable. For example, either the positive and negative prefixes or the
 * suffixes must be distinct for {@link #parse} to be able to distinguish
 * positive from negative values. Another example is that the decimal separator
 * and thousands separator should be distinct characters, or parsing will be
 * impossible.
 *

 * The grouping separator is a character that separates clusters of
 * integer digits to make large numbers more legible. It is commonly used for
 * thousands, but in some locales it separates ten-thousands. The grouping
 * size
 * is the number of digits between the grouping separators, such as 3 for
 * "100,000,000" or 4 for "1 0000 0000". There are actually two different
 * grouping sizes: One used for the least significant integer digits, the
 * primary grouping size, and one used for all others, the
 * secondary grouping size. In most locales these are the same, but
 * sometimes they are different. For example, if the primary grouping interval
 * is 3, and the secondary is 2, then this corresponds to the pattern
 * "#,##,##0", and the number 123456789 is formatted as "12,34,56,789". If a
 * pattern contains multiple grouping separators, the interval between the last
 * one and the end of the integer defines the primary grouping size, and the
 * interval between the last two defines the secondary grouping size. All others
 * are ignored, so "#,##,###,####", "###,###,####" and "##,#,###,####" produce
 * the same result.
 *

 * Illegal patterns, such as "#.#.#" or "#.###,###", will cause
 * {@code DecimalFormat} to throw an {@link IllegalArgumentException} with a
 * message that describes the problem.
 *
Pattern BNF

 *
 *

 * pattern    := subpattern (';' subpattern)?
 * subpattern := prefix? number exponent? suffix?
 * number     := (integer ('.' fraction)?) | sigDigits
 * prefix     := '\\u0000'..'\\uFFFD' - specialCharacters
 * suffix     := '\\u0000'..'\\uFFFD' - specialCharacters
 * integer    := '#'* '0'* '0'
 * fraction   := '0'* '#'*
 * sigDigits  := '#'* '@' '@'* '#'*
 * exponent   := 'E' '+'? '0'* '0'
 * padSpec    := '*' padChar
 * padChar    := '\\u0000'..'\\uFFFD' - quote
 *
 * Notation:
 *   X*       0 or more instances of X
 *   X?       0 or 1 instances of X
 *   X|Y      either X or Y
 *   C..D     any character from C up to D, inclusive
 *   S-T      characters in S, except those in T
 *

 *
 * The first subpattern is for positive numbers. The second (optional)
 * subpattern is for negative numbers.
 *

 * Not indicated in the BNF syntax above:
 *

 *
The grouping separator ',' can occur inside the integer and sigDigits
 * elements, between any two pattern characters of that element, as long as the
 * integer or sigDigits element is not followed by the exponent element.
 *
NEW  Two
 * grouping intervals are recognized: The one between the decimal point and the
 * first grouping symbol and the one between the first and second grouping
 * symbols. These intervals are identical in most locales, but in some locales
 * they differ. For example, the pattern "#,##,###" formats the number
 * 123456789 as "12,34,56,789".

 *
 NEW  The pad
 * specifier {@code padSpec} may appear before the prefix, after the prefix,
 * before the suffix, after the suffix or not at all.
 *

 *
Parsing

 *

 * {@code DecimalFormat} parses all Unicode characters that represent decimal
 * digits, as defined by {@link Character#digit(int, int)}. In addition,
 * {@code DecimalFormat} also recognizes as digits the ten consecutive
 * characters starting with the localized zero digit defined in the
 * {@link DecimalFormatSymbols} object. During formatting, the
 * {@link DecimalFormatSymbols}-based digits are written out.
 *

 * During parsing, grouping separators are ignored.
 *

 * If {@link #parse(String, ParsePosition)} fails to parse a string, it returns
 * {@code null} and leaves the parse position unchanged.
 *
Formatting

 *

 * Formatting is guided by several parameters, all of which can be specified
 * either using a pattern or using the API. The following description applies to
 * formats that do not use scientific notation or significant digits.
 *

 *
If the number of actual integer digits exceeds the
 * maximum integer digits, then only the least significant digits
 * are shown. For example, 1997 is formatted as "97" if maximum integer digits
 * is set to 2.
 *
If the number of actual integer digits is less than the
 * minimum integer digits, then leading zeros are added. For
 * example, 1997 is formatted as "01997" if minimum integer digits is set to 5.
 *
If the number of actual fraction digits exceeds the maximum
 * fraction digits,
 * then half-even rounding is performed to the maximum fraction digits. For
 * example, 0.125 is formatted as "0.12" if the maximum fraction digits is 2.
 *
If the number of actual fraction digits is less than the
 * minimum fraction digits, then trailing zeros are added. For
 * example, 0.125 is formatted as "0.1250" if the mimimum fraction digits is set
 * to 4.
 *
Trailing fractional zeros are not displayed if they occur j
 * positions after the decimal, where j is less than the maximum
 * fraction digits. For example, 0.10004 is formatted as "0.1" if the maximum
 * fraction digits is four or less.
 *

 *

 * Special Values
 *

 * {@code NaN} is represented as a single character, typically
 * {@code \uFFFD}. This character is determined by the
 * {@link DecimalFormatSymbols} object. This is the only value for which the
 * prefixes and suffixes are not used.
 *

 * Infinity is represented as a single character, typically {@code \u221E},
 * with the positive or negative prefixes and suffixes applied. The infinity
 * character is determined by the {@link DecimalFormatSymbols} object.
 *
Scientific Notation

 *
 *

 * Numbers in scientific notation are expressed as the product of a mantissa and
 * a power of ten, for example, 1234 can be expressed as 1.234 x 103.
 * The mantissa is typically in the half-open interval [1.0, 10.0) or sometimes
 * [0.0, 1.0), but it does not need to be. {@code DecimalFormat} supports
 * arbitrary mantissas. {@code DecimalFormat} can be instructed to use
 * scientific notation through the API or through the pattern. In a pattern, the
 * exponent character immediately followed by one or more digit characters
 * indicates scientific notation. Example: "0.###E0" formats the number 1234 as
 * "1.234E3".
 *

 *
The number of digit characters after the exponent character gives the
 * minimum exponent digit count. There is no maximum. Negative exponents are
 * formatted using the localized minus sign, not the prefix and
 * suffix from the pattern. This allows patterns such as "0.###E0 m/s". To
 * prefix positive exponents with a localized plus sign, specify '+' between the
 * exponent and the digits: "0.###E+0" will produce formats "1E+1", "1E+0",
 * "1E-1", etc. (In localized patterns, use the localized plus sign rather than
 * '+'.)
 *
The minimum number of integer digits is achieved by adjusting the
 * exponent. Example: 0.00123 formatted with "00.###E0" yields "12.3E-4". This
 * only happens if there is no maximum number of integer digits. If there is a
 * maximum, then the minimum number of integer digits is fixed at one.
 *
The maximum number of integer digits, if present, specifies the exponent
 * grouping. The most common use of this is to generate engineering
 * notation,
 * in which the exponent is a multiple of three, e.g., "##0.###E0". The number
 * 12345 is formatted using "##0.###E0" as "12.345E3".
 *
When using scientific notation, the formatter controls the digit counts
 * using significant digits logic. The maximum number of significant digits
 * limits the total number of integer and fraction digits that will be shown in
 * the mantissa; it does not affect parsing. For example, 12345 formatted with
 * "##0.##E0" is "12.3E3". See the section on significant digits for more
 * details.
 *
The number of significant digits shown is determined as follows: If no
 * significant digits are used in the pattern then the minimum number of
 * significant digits shown is one, the maximum number of significant digits
 * shown is the sum of the minimum integer and
 * maximum fraction digits, and it is unaffected by the maximum
 * integer digits. If this sum is zero, then all significant digits are shown.
 * If significant digits are used in the pattern then the number of integer
 * digits is fixed at one and there is no exponent grouping.
 *
Exponential patterns may not contain grouping separators.
 *

 *
 *
 NEW  Significant
 * Digits

 *

 *  {@code DecimalFormat} has two ways of controlling how many digits are
 * shown: (a) significant digit counts or (b) integer and fraction digit counts.
 * Integer and fraction digit counts are described above. When a formatter uses
 * significant digits counts, the number of integer and fraction digits is not
 * specified directly, and the formatter settings for these counts are ignored.
 * Instead, the formatter uses as many integer and fraction digits as required
 * to display the specified number of significant digits.
 *
Examples:

 *

 *

 * Pattern
 * Minimum significant digits
 * Maximum significant digits
 * Number
 * Output of format()
 *

 *

 * {@code @@@}
 * 3
 * 3
 * 12345
 * {@code 12300}
 *

 *

 * {@code @@@}
 * 3
 * 3
 * 0.12345
 * {@code 0.123}
 *

 *

 * {@code @@##}
 * 2
 * 4
 * 3.14159
 * {@code 3.142}
 *

 *

 * {@code @@##}
 * 2
 * 4
 * 1.23004
 * {@code 1.23}
 *

 *

 *

 *
Significant digit counts may be expressed using patterns that specify a
 * minimum and maximum number of significant digits. These are indicated by the
 * {@code '@'} and {@code '#'} characters. The minimum number of significant
 * digits is the number of {@code '@'} characters. The maximum number of
 * significant digits is the number of {@code '@'} characters plus the number of
 * {@code '#'} characters following on the right. For example, the pattern
 * {@code "@@@"} indicates exactly 3 significant digits. The pattern
 * {@code "@##"} indicates from 1 to 3 significant digits. Trailing zero digits
 * to the right of the decimal separator are suppressed after the minimum number
 * of significant digits have been shown. For example, the pattern {@code "@##"}
 * formats the number 0.1203 as {@code "0.12"}.
 *
If a pattern uses significant digits, it may not contain a decimal
 * separator, nor the {@code '0'} pattern character. Patterns such as
 * {@code "@00"} or {@code "@.###"} are disallowed.
 *
Any number of {@code '#'} characters may be prepended to the left of the
 * leftmost {@code '@'} character. These have no effect on the minimum and
 * maximum significant digit counts, but may be used to position grouping
 * separators. For example, {@code "#,#@#"} indicates a minimum of one
 * significant digit, a maximum of two significant digits, and a grouping size
 * of three.
 *
In order to enable significant digits formatting, use a pattern
 * containing the {@code '@'} pattern character.
 *
In order to disable significant digits formatting, use a pattern that
 * does not contain the {@code '@'} pattern character.
 *
The number of significant digits has no effect on parsing.
 *
Significant digits may be used together with exponential notation. Such
 * patterns are equivalent to a normal exponential pattern with a minimum and
 * maximum integer digit count of one, a minimum fraction digit count of the
 * number of '@' characters in the pattern - 1, and a maximum fraction digit
 * count of the number of '@' and '#' characters in the pattern - 1. For
 * example, the pattern {@code "@@###E0"} is equivalent to {@code "0.0###E0"}.
 *
If signficant digits are in use then the integer and fraction digit
 * counts, as set via the API, are ignored.
 *

 *
 NEW  Padding

 *

 * {@code DecimalFormat} supports padding the result of {@code format} to a
 * specific width. Padding may be specified either through the API or through
 * the pattern syntax. In a pattern, the pad escape character followed by a
 * single pad character causes padding to be parsed and formatted. The pad
 * escape character is '*' in unlocalized patterns. For example,
 * {@code "$*x#,##0.00"} formats 123 to {@code "$xx123.00"}, and 1234 to
 * {@code "$1,234.00"}.
 *

 *
When padding is in effect, the width of the positive subpattern,
 * including prefix and suffix, determines the format width. For example, in the
 * pattern {@code "* #0 o''clock"}, the format width is 10.

 *
The width is counted in 16-bit code units (Java {@code char}s).

 *
Some parameters which usually do not matter have meaning when padding is
 * used, because the pattern width is significant with padding. In the pattern "*
 * ##,##,#,##0.##", the format width is 14. The initial characters "##,##," do
 * not affect the grouping size or maximum integer digits, but they do affect
 * the format width.

 *
Padding may be inserted at one of four locations: before the prefix,
 * after the prefix, before the suffix or after the suffix. If padding is
 * specified in any other location, {@link #applyPattern} throws an {@link
 * IllegalArgumentException}. If there is no prefix, before the prefix and after
 * the prefix are equivalent, likewise for the suffix.

 *
When specified in a pattern, the 16-bit {@code char} immediately
 * following the pad escape is the pad character. This may be any character,
 * including a special pattern character. That is, the pad escape
 * escapes the following character. If there is no character after
 * the pad escape, then the pattern is illegal.

 *

 *
Synchronization

 *

 * {@code DecimalFormat} objects are not synchronized. Multiple threads should
 * not access one formatter concurrently.
 *
 * @see Format
 * @see NumberFormat
 */
public class DecimalFormat extends NumberFormat {

    private static final long serialVersionUID = 864413376551465018L;

    private transient boolean parseBigDecimal = false;

    private transient DecimalFormatSymbols symbols;

    private transient com.ibm.icu.text.DecimalFormat dform;

    private transient com.ibm.icu.text.DecimalFormatSymbols icuSymbols;

    private static final int CURRENT_SERIAL_VERTION = 3;

    private transient int serialVersionOnStream = 3;

    /**
     * Constructs a new {@code DecimalFormat} for formatting and parsing numbers
     * for the default locale.
     */
    public DecimalFormat() {
        Locale locale = Locale.getDefault();
        icuSymbols = new com.ibm.icu.text.DecimalFormatSymbols(locale);
        symbols = new DecimalFormatSymbols(locale);
        dform = new com.ibm.icu.text.DecimalFormat();

        super.setMaximumFractionDigits(dform.getMaximumFractionDigits());
        super.setMaximumIntegerDigits(dform.getMaximumIntegerDigits());
        super.setMinimumFractionDigits(dform.getMinimumFractionDigits());
        super.setMinimumIntegerDigits(dform.getMinimumIntegerDigits());
    }

    /**
     * Constructs a new {@code DecimalFormat} using the specified non-localized
     * pattern and the {@code DecimalFormatSymbols} for the default Locale.
     *
     * @param pattern
     *            the non-localized pattern.
     * @throws IllegalArgumentException
     *            if the pattern cannot be parsed.
     */
    public DecimalFormat(String pattern) {
        Locale locale = Locale.getDefault();
        icuSymbols = new com.ibm.icu.text.DecimalFormatSymbols(locale);
        symbols = new DecimalFormatSymbols(locale);
        dform = new com.ibm.icu.text.DecimalFormat(pattern, icuSymbols);

        super.setMaximumFractionDigits(dform.getMaximumFractionDigits());
        super.setMaximumIntegerDigits(dform.getMaximumIntegerDigits());
        super.setMinimumFractionDigits(dform.getMinimumFractionDigits());
        super.setMinimumIntegerDigits(dform.getMinimumIntegerDigits());
    }

    /**
     * Constructs a new {@code DecimalFormat} using the specified non-localized
     * pattern and {@code DecimalFormatSymbols}.
     *
     * @param pattern
     *            the non-localized pattern.
     * @param value
     *            the DecimalFormatSymbols.
     * @throws IllegalArgumentException
     *            if the pattern cannot be parsed.
     */
    public DecimalFormat(String pattern, DecimalFormatSymbols value) {
        symbols = (DecimalFormatSymbols) value.clone();
        Locale locale = symbols.getLocale();
        icuSymbols = new com.ibm.icu.text.DecimalFormatSymbols(locale);
        copySymbols(icuSymbols, symbols);

        dform = new com.ibm.icu.text.DecimalFormat(pattern, icuSymbols);

        super.setMaximumFractionDigits(dform.getMaximumFractionDigits());
        super.setMaximumIntegerDigits(dform.getMaximumIntegerDigits());
        super.setMinimumFractionDigits(dform.getMinimumFractionDigits());
        super.setMinimumIntegerDigits(dform.getMinimumIntegerDigits());
    }

    DecimalFormat(String pattern, DecimalFormatSymbols value, com.ibm.icu.text.DecimalFormat icuFormat) {
        symbols = value;
        icuSymbols = value.getIcuSymbols();
        dform = icuFormat;

        super.setMaximumFractionDigits(dform.getMaximumFractionDigits());
        super.setMaximumIntegerDigits(dform.getMaximumIntegerDigits());
        super.setMinimumFractionDigits(dform.getMinimumFractionDigits());
        super.setMinimumIntegerDigits(dform.getMinimumIntegerDigits());
    }

    /**
     * Changes the pattern of this decimal format to the specified pattern which
     * uses localized pattern characters.
     *
     * @param pattern
     *            the localized pattern.
     * @throws IllegalArgumentException
     *            if the pattern cannot be parsed.
     */
    public void applyLocalizedPattern(String pattern) {
        dform.applyLocalizedPattern(pattern);
        super.setMaximumFractionDigits(dform.getMaximumFractionDigits());
        super.setMaximumIntegerDigits(dform.getMaximumIntegerDigits());
        super.setMinimumFractionDigits(dform.getMinimumFractionDigits());
        super.setMinimumIntegerDigits(dform.getMinimumIntegerDigits());
    }

    /**
     * Changes the pattern of this decimal format to the specified pattern which
     * uses non-localized pattern characters.
     *
     * @param pattern
     *            the non-localized pattern.
     * @throws IllegalArgumentException
     *            if the pattern cannot be parsed.
     */
    public void applyPattern(String pattern) {

        dform.applyPattern(pattern);
        super.setMaximumFractionDigits(dform.getMaximumFractionDigits());
        super.setMaximumIntegerDigits(dform.getMaximumIntegerDigits());
        super.setMinimumFractionDigits(dform.getMinimumFractionDigits());
        super.setMinimumIntegerDigits(dform.getMinimumIntegerDigits());
    }

    /**
     * Returns a new instance of {@code DecimalFormat} with the same pattern and
     * properties as this decimal format.
     *
     * @return a shallow copy of this decimal format.
     * @see java.lang.Cloneable
     */
    @Override
    public Object clone() {
        DecimalFormat clone = (DecimalFormat) super.clone();
        clone.dform = (com.ibm.icu.text.DecimalFormat) dform.clone();
        clone.symbols = (DecimalFormatSymbols) symbols.clone();
        return clone;
    }

    /**
     * Compares the specified object to this decimal format and indicates if
     * they are equal. In order to be equal, {@code object} must be an instance
     * of {@code DecimalFormat} with the same pattern and properties.
     *
     * @param object
     *            the object to compare with this object.
     * @return {@code true} if the specified object is equal to this decimal
     *         format; {@code false} otherwise.
     * @see #hashCode
     */
    @Override
    public boolean equals(Object object) {
        if (this == object) {
            return true;
        }
        if (!(object instanceof DecimalFormat)) {
            return false;
        }
        DecimalFormat format = (DecimalFormat) object;
        return (this.dform == null ? format.dform == null : this.dform
                .equals(format.dform));
    }

    /**
     * Formats the specified object using the rules of this decimal format and
     * returns an {@code AttributedCharacterIterator} with the formatted number
     * and attributes.
     *
     * @param object
     *            the object to format.
     * @return an AttributedCharacterIterator with the formatted number and
     *         attributes.
     * @throws IllegalArgumentException
     *             if {@code object} cannot be formatted by this format.
     * @throws NullPointerException
     *             if {@code object} is {@code null}.
     */
    @Override
    public AttributedCharacterIterator formatToCharacterIterator(Object object) {
        if (object == null) {
            throw new NullPointerException();
        }
        return dform.formatToCharacterIterator(object);
    }

    /**
     * Formats the specified double value as a string using the pattern of this
     * decimal format and appends the string to the specified string buffer.
     *

     * If the {@code field} member of {@code position} contains a value
     * specifying a format field, then its {@code beginIndex} and
     * {@code endIndex} members will be updated with the position of the first
     * occurrence of this field in the formatted text.
     *
     * @param value
     *            the double to format.
     * @param buffer
     *            the target string buffer to append the formatted double value
     *            to.
     * @param position
     *            on input: an optional alignment field; on output: the offsets
     *            of the alignment field in the formatted text.
     * @return the string buffer.
     */
    @Override
    public StringBuffer format(double value, StringBuffer buffer,
            FieldPosition position) {
        return dform.format(value, buffer, position);
    }

    /**
     * Formats the specified long value as a string using the pattern of this
     * decimal format and appends the string to the specified string buffer.
     *

     * If the {@code field} member of {@code position} contains a value
     * specifying a format field, then its {@code beginIndex} and
     * {@code endIndex} members will be updated with the position of the first
     * occurrence of this field in the formatted text.
     *
     * @param value
     *            the long to format.
     * @param buffer
     *            the target string buffer to append the formatted long value
     *            to.
     * @param position
     *            on input: an optional alignment field; on output: the offsets
     *            of the alignment field in the formatted text.
     * @return the string buffer.
     */
    @Override
    public StringBuffer format(long value, StringBuffer buffer,
            FieldPosition position) {
        return dform.format(value, buffer, position);
    }

    /**
     * Formats the specified object as a string using the pattern of this
     * decimal format and appends the string to the specified string buffer.
     *

     * If the {@code field} member of {@code position} contains a value
     * specifying a format field, then its {@code beginIndex} and
     * {@code endIndex} members will be updated with the position of the first
     * occurrence of this field in the formatted text.
     *
     * @param number
     *            the object to format.
     * @param toAppendTo
     *            the target string buffer to append the formatted number to.
     * @param pos
     *            on input: an optional alignment field; on output: the offsets
     *            of the alignment field in the formatted text.
     * @return the string buffer.
     * @throws IllegalArgumentException
     *             if {@code number} is not an instance of {@code Number}.
     * @throws NullPointerException
     *             if {@code toAppendTo} or {@code pos} is {@code null}.
     */
    @Override
    public final StringBuffer format(Object number, StringBuffer toAppendTo,
            FieldPosition pos) {
        if (!(number instanceof Number)) {
            throw new IllegalArgumentException();
        }
        if (toAppendTo == null || pos == null) {
            throw new NullPointerException();
        }
        if (number instanceof BigInteger || number instanceof BigDecimal) {
            return dform.format(number, toAppendTo, pos);
        }
        return super.format(number, toAppendTo, pos);
    }

    /**
     * Returns the {@code DecimalFormatSymbols} used by this decimal format.
     *
     * @return a copy of the {@code DecimalFormatSymbols} used by this decimal
     *         format.
     */
    public DecimalFormatSymbols getDecimalFormatSymbols() {
        return (DecimalFormatSymbols) symbols.clone();
    }

    /**
     * Returns the currency used by this decimal format.
     *
     * @return the currency used by this decimal format.
     * @see DecimalFormatSymbols#getCurrency()
     */
    @Override
    public Currency getCurrency() {
        final com.ibm.icu.util.Currency cur = dform.getCurrency();
        final String code = (cur == null) ? "XXX" : cur.getCurrencyCode(); //$NON-NLS-1$

        return Currency.getInstance(code);
    }

    /**
     * Returns the number of digits grouped together by the grouping separator.
     * This only allows to get the primary grouping size. There is no API to get
     * the secondary grouping size.
     *
     * @return the number of digits grouped together.
     */
    public int getGroupingSize() {
        return dform.getGroupingSize();
    }

    /**
     * Returns the multiplier which is applied to the number before formatting
     * or after parsing.
     *
     * @return the multiplier.
     */
    public int getMultiplier() {
        return dform.getMultiplier();
    }

    /**
     * Returns the prefix which is formatted or parsed before a negative number.
     *
     * @return the negative prefix.
     */
    public String getNegativePrefix() {
        return dform.getNegativePrefix();
    }

    /**
     * Returns the suffix which is formatted or parsed after a negative number.
     *
     * @return the negative suffix.
     */
    public String getNegativeSuffix() {
        return dform.getNegativeSuffix();
    }

    /**
     * Returns the prefix which is formatted or parsed before a positive number.
     *
     * @return the positive prefix.
     */
    public String getPositivePrefix() {
        return dform.getPositivePrefix();
    }

    /**
     * Returns the suffix which is formatted or parsed after a positive number.
     *
     * @return the positive suffix.
     */
    public String getPositiveSuffix() {
        return dform.getPositiveSuffix();
    }

    @Override
    public int hashCode() {
        return dform.hashCode();
    }

    /**
     * Indicates whether the decimal separator is shown when there are no
     * fractional digits.
     *
     * @return {@code true} if the decimal separator should always be formatted;
     *         {@code false} otherwise.
     */
    public boolean isDecimalSeparatorAlwaysShown() {
        return dform.isDecimalSeparatorAlwaysShown();
    }

    /**
     * This value indicates whether the return object of the parse operation is
     * of type {@code BigDecimal}. This value defaults to {@code false}.
     *
     * @return {@code true} if parse always returns {@code BigDecimals},
     *         {@code false} if the type of the result is {@code Long} or
     *         {@code Double}.
     */
    public boolean isParseBigDecimal() {
        return this.parseBigDecimal;
    }

    /**
     * Sets the flag that indicates whether numbers will be parsed as integers.
     * When this decimal format is used for parsing and this value is set to
     * {@code true}, then the resulting numbers will be of type
     * {@code java.lang.Integer}. Special cases are NaN, positive and negative
     * infinity, which are still returned as {@code java.lang.Double}.
     *
     *
     * @param value
     *            {@code true} that the resulting numbers of parse operations
     *            will be of type {@code java.lang.Integer} except for the
     *            special cases described above.
     */
    @Override
    public void setParseIntegerOnly(boolean value) {
        // In this implementation, com.ibm.icu.text.DecimalFormat is wrapped to
        // fulfill most of the format and parse feature. And this method is
        // delegated to the wrapped instance of com.ibm.icu.text.DecimalFormat.

        dform.setParseIntegerOnly(value);
    }

    /**
     * Indicates whether parsing with this decimal format will only
     * return numbers of type {@code java.lang.Integer}.
     *
     * @return {@code true} if this {@code DecimalFormat}'s parse method only
     *         returns {@code java.lang.Integer}; {@code false} otherwise.
     */
    @Override
    public boolean isParseIntegerOnly() {
        return dform.isParseIntegerOnly();
    }

    private static final Double NEGATIVE_ZERO_DOUBLE = new Double(-0.0);

    /**
     * Parses a {@code Long} or {@code Double} from the specified string
     * starting at the index specified by {@code position}. If the string is
     * successfully parsed then the index of the {@code ParsePosition} is
     * updated to the index following the parsed text. On error, the index is
     * unchanged and the error index of {@code ParsePosition} is set to the
     * index where the error occurred.
     *
     * @param string
     *            the string to parse.
     * @param position
     *            input/output parameter, specifies the start index in
     *            {@code string} from where to start parsing. If parsing is
     *            successful, it is updated with the index following the parsed
     *            text; on error, the index is unchanged and the error index is
     *            set to the index where the error occurred.
     * @return a {@code Long} or {@code Double} resulting from the parse or
     *         {@code null} if there is an error. The result will be a
     *         {@code Long} if the parsed number is an integer in the range of a
     *         long, otherwise the result is a {@code Double}. If
     *         {@code isParseBigDecimal} is {@code true} then it returns the
     *         result as a {@code BigDecimal}.
     */
    @Override
    public Number parse(String string, ParsePosition position) {
        Number number = dform.parse(string, position);
        if (null == number) {
            return null;
        }
        if (this.isParseBigDecimal()) {
            if (number instanceof Long) {
                return new BigDecimal(number.longValue());
            }
            if ((number instanceof Double) && !((Double) number).isInfinite()
                    && !((Double) number).isNaN()) {

                return new BigDecimal(number.doubleValue());
            }
            if (number instanceof BigInteger) {
                return new BigDecimal(number.doubleValue());
            }
            if (number instanceof com.ibm.icu.math.BigDecimal) {
                return new BigDecimal(number.toString());
            }
            return number;
        }
        if ((number instanceof com.ibm.icu.math.BigDecimal)
                || (number instanceof BigInteger)) {
            return new Double(number.doubleValue());
        }

        if (this.isParseIntegerOnly() && number.equals(NEGATIVE_ZERO_DOUBLE)) {
            return new Long(0);
        }
        return number;

    }

    /**
     * Sets the {@code DecimalFormatSymbols} used by this decimal format.
     *
     * @param value
     *            the {@code DecimalFormatSymbols} to set.
     */
    public void setDecimalFormatSymbols(DecimalFormatSymbols value) {
        if (value != null) {
            symbols = (DecimalFormatSymbols) value.clone();
            icuSymbols = dform.getDecimalFormatSymbols();
            copySymbols(icuSymbols, symbols);
            dform.setDecimalFormatSymbols(icuSymbols);
        }
    }

    /**
     * Sets the currency used by this decimal format. The min and max fraction
     * digits remain the same.
     *
     * @param currency
     *            the currency this {@code DecimalFormat} should use.
     * @see DecimalFormatSymbols#setCurrency(Currency)
     */
    @Override
    public void setCurrency(Currency currency) {
        dform.setCurrency(com.ibm.icu.util.Currency.getInstance(currency
                .getCurrencyCode()));
        symbols.setCurrency(currency);
    }

    /**
     * Sets whether the decimal separator is shown when there are no fractional
     * digits.
     *
     * @param value
     *            {@code true} if the decimal separator should always be
     *            formatted; {@code false} otherwise.
     */
    public void setDecimalSeparatorAlwaysShown(boolean value) {
        dform.setDecimalSeparatorAlwaysShown(value);
    }

    /**
     * Sets the number of digits grouped together by the grouping separator.
     * This only allows to set the primary grouping size; the secondary grouping
     * size can only be set with a pattern.
     *
     * @param value
     *            the number of digits grouped together.
     */
    public void setGroupingSize(int value) {
        dform.setGroupingSize(value);
    }

    /**
     * Sets whether or not grouping will be used in this format. Grouping
     * affects both parsing and formatting.
     *
     * @param value
     *            {@code true} if grouping is used; {@code false} otherwise.
     */
    @Override
    public void setGroupingUsed(boolean value) {
        dform.setGroupingUsed(value);
    }

    /**
     * Indicates whether grouping will be used in this format.
     *
     * @return {@code true} if grouping is used; {@code false} otherwise.
     */
    @Override
    public boolean isGroupingUsed() {
        return dform.isGroupingUsed();
    }

    /**
     * Sets the maximum number of fraction digits that are printed when
     * formatting numbers other than {@code BigDecimal} and {@code BigInteger}.
     * If the maximum is less than the number of fraction digits, the least
     * significant digits are truncated. If the value passed is bigger than 340
     * then it is replaced by 340. If the value passed is negative then it is
     * replaced by 0.
     *
     * @param value
     *            the maximum number of fraction digits.
     */
    @Override
    public void setMaximumFractionDigits(int value) {
        super.setMaximumFractionDigits(value);
        dform.setMaximumFractionDigits(value);
    }

    /**
     * Sets the maximum number of integer digits that are printed when
     * formatting numbers other than {@code BigDecimal} and {@code BigInteger}.
     * If the maximum is less than the number of integer digits, the most
     * significant digits are truncated. If the value passed is bigger than 309
     * then it is replaced by 309. If the value passed is negative then it is
     * replaced by 0.
     *
     * @param value
     *            the maximum number of integer digits.
     */
    @Override
    public void setMaximumIntegerDigits(int value) {
        super.setMaximumIntegerDigits(value);
        dform.setMaximumIntegerDigits(value);
    }

    /**
     * Sets the minimum number of fraction digits that are printed when
     * formatting numbers other than {@code BigDecimal} and {@code BigInteger}.
     * If the value passed is bigger than 340 then it is replaced by 340. If the
     * value passed is negative then it is replaced by 0.
     *
     * @param value
     *            the minimum number of fraction digits.
     */
    @Override
    public void setMinimumFractionDigits(int value) {
        super.setMinimumFractionDigits(value);
        dform.setMinimumFractionDigits(value);
    }

    /**
     * Sets the minimum number of integer digits that are printed when
     * formatting numbers other than {@code BigDecimal} and {@code BigInteger}.
     * If the value passed is bigger than 309 then it is replaced by 309. If the
     * value passed is negative then it is replaced by 0.
     *
     * @param value
     *            the minimum number of integer digits.
     */
    @Override
    public void setMinimumIntegerDigits(int value) {
        super.setMinimumIntegerDigits(value);
        dform.setMinimumIntegerDigits(value);
    }

    /**
     * Sets the multiplier which is applied to the number before formatting or
     * after parsing.
     *
     * @param value
     *            the multiplier.
     */
    public void setMultiplier(int value) {
        dform.setMultiplier(value);
    }

    /**
     * Sets the prefix which is formatted or parsed before a negative number.
     *
     * @param value
     *            the negative prefix.
     */
    public void setNegativePrefix(String value) {
        dform.setNegativePrefix(value);
    }

    /**
     * Sets the suffix which is formatted or parsed after a negative number.
     *
     * @param value
     *            the negative suffix.
     */
    public void setNegativeSuffix(String value) {
        dform.setNegativeSuffix(value);
    }

    /**
     * Sets the prefix which is formatted or parsed before a positive number.
     *
     * @param value
     *            the positive prefix.
     */
    public void setPositivePrefix(String value) {
        dform.setPositivePrefix(value);
    }

    /**
     * Sets the suffix which is formatted or parsed after a positive number.
     *
     * @param value
     *            the positive suffix.
     */
    public void setPositiveSuffix(String value) {
        dform.setPositiveSuffix(value);
    }

    /**
     * Sets the behaviour of the parse method. If set to {@code true} then all
     * the returned objects will be of type {@code BigDecimal}.
     *
     * @param newValue
     *            {@code true} if all the returned objects should be of type
     *            {@code BigDecimal}; {@code false} otherwise.
     */
    public void setParseBigDecimal(boolean newValue) {
        this.parseBigDecimal = newValue;
    }

    /**
     * Returns the pattern of this decimal format using localized pattern
     * characters.
     *
     * @return the localized pattern.
     */
    public String toLocalizedPattern() {
        return dform.toLocalizedPattern();
    }

    /**
     * Returns the pattern of this decimal format using non-localized pattern
     * characters.
     *
     * @return the non-localized pattern.
     */
    public String toPattern() {
        return dform.toPattern();
    }

    // the fields list to be serialized
    private static final ObjectStreamField[] serialPersistentFields = {
            new ObjectStreamField("positivePrefix", String.class), //$NON-NLS-1$
            new ObjectStreamField("positiveSuffix", String.class), //$NON-NLS-1$
            new ObjectStreamField("negativePrefix", String.class), //$NON-NLS-1$
            new ObjectStreamField("negativeSuffix", String.class), //$NON-NLS-1$
            new ObjectStreamField("posPrefixPattern", String.class), //$NON-NLS-1$
            new ObjectStreamField("posSuffixPattern", String.class), //$NON-NLS-1$
            new ObjectStreamField("negPrefixPattern", String.class), //$NON-NLS-1$
            new ObjectStreamField("negSuffixPattern", String.class), //$NON-NLS-1$
            new ObjectStreamField("multiplier", int.class), //$NON-NLS-1$
            new ObjectStreamField("groupingSize", byte.class), //$NON-NLS-1$
            new ObjectStreamField("decimalSeparatorAlwaysShown", boolean.class), //$NON-NLS-1$
            new ObjectStreamField("parseBigDecimal", boolean.class), //$NON-NLS-1$
            new ObjectStreamField("symbols", DecimalFormatSymbols.class), //$NON-NLS-1$
            new ObjectStreamField("useExponentialNotation", boolean.class), //$NON-NLS-1$
            new ObjectStreamField("minExponentDigits", byte.class), //$NON-NLS-1$
            new ObjectStreamField("maximumIntegerDigits", int.class), //$NON-NLS-1$
            new ObjectStreamField("minimumIntegerDigits", int.class), //$NON-NLS-1$
            new ObjectStreamField("maximumFractionDigits", int.class), //$NON-NLS-1$
            new ObjectStreamField("minimumFractionDigits", int.class), //$NON-NLS-1$
            new ObjectStreamField("serialVersionOnStream", int.class), }; //$NON-NLS-1$

    /**
     * Writes serialized fields following serialized forms specified by Java
     * specification.
     *
     * @param stream
     *            the output stream to write serialized bytes
     * @throws IOException
     *             if some I/O error occurs
     * @throws ClassNotFoundException
     */
    @SuppressWarnings("nls")
    private void writeObject(ObjectOutputStream stream) throws IOException,
            ClassNotFoundException {
        ObjectOutputStream.PutField fields = stream.putFields();
        fields.put("positivePrefix", dform.getPositivePrefix());
        fields.put("positiveSuffix", dform.getPositiveSuffix());
        fields.put("negativePrefix", dform.getNegativePrefix());
        fields.put("negativeSuffix", dform.getNegativeSuffix());
        String posPrefixPattern = (String) Format.getInternalField(
                "posPrefixPattern", dform);
        fields.put("posPrefixPattern", posPrefixPattern);
        String posSuffixPattern = (String) Format.getInternalField(
                "posSuffixPattern", dform);
        fields.put("posSuffixPattern", posSuffixPattern);
        String negPrefixPattern = (String) Format.getInternalField(
                "negPrefixPattern", dform);
        fields.put("negPrefixPattern", negPrefixPattern);
        String negSuffixPattern = (String) Format.getInternalField(
                "negSuffixPattern", dform);
        fields.put("negSuffixPattern", negSuffixPattern);
        fields.put("multiplier", dform.getMultiplier());
        fields.put("groupingSize", (byte) dform.getGroupingSize());
        fields.put("decimalSeparatorAlwaysShown", dform
                .isDecimalSeparatorAlwaysShown());
        fields.put("parseBigDecimal", parseBigDecimal);
        fields.put("symbols", symbols);
        boolean useExponentialNotation = ((Boolean) Format.getInternalField(
                "useExponentialNotation", dform)).booleanValue();
        fields.put("useExponentialNotation", useExponentialNotation);
        byte minExponentDigits = ((Byte) Format.getInternalField(
                "minExponentDigits", dform)).byteValue();
        fields.put("minExponentDigits", minExponentDigits);
        fields.put("maximumIntegerDigits", dform.getMaximumIntegerDigits());
        fields.put("minimumIntegerDigits", dform.getMinimumIntegerDigits());
        fields.put("maximumFractionDigits", dform.getMaximumFractionDigits());
        fields.put("minimumFractionDigits", dform.getMinimumFractionDigits());
        fields.put("serialVersionOnStream", CURRENT_SERIAL_VERTION);
        stream.writeFields();
    }

    /**
     * Reads serialized fields following serialized forms specified by Java
     * specification.
     *
     * @param stream
     *            the input stream to read serialized bytes
     * @throws IOException
     *             if some I/O error occurs
     * @throws ClassNotFoundException
     *             if some class of serialized objects or fields cannot be found
     */
    @SuppressWarnings("nls")
    private void readObject(ObjectInputStream stream) throws IOException,
            ClassNotFoundException {

        ObjectInputStream.GetField fields = stream.readFields();
        String positivePrefix = (String) fields.get("positivePrefix", "");
        String positiveSuffix = (String) fields.get("positiveSuffix", "");
        String negativePrefix = (String) fields.get("negativePrefix", "-");
        String negativeSuffix = (String) fields.get("negativeSuffix", "");

        String posPrefixPattern = (String) fields.get("posPrefixPattern", "");
        String posSuffixPattern = (String) fields.get("posSuffixPattern", "");
        String negPrefixPattern = (String) fields.get("negPrefixPattern", "-");
        String negSuffixPattern = (String) fields.get("negSuffixPattern", "");

        int multiplier = fields.get("multiplier", 1);
        byte groupingSize = fields.get("groupingSize", (byte) 3);
        boolean decimalSeparatorAlwaysShown = fields.get(
                "decimalSeparatorAlwaysShown", false);
        boolean parseBigDecimal = fields.get("parseBigDecimal", false);
        symbols = (DecimalFormatSymbols) fields.get("symbols", null);

        boolean useExponentialNotation = fields.get("useExponentialNotation",
                false);
        byte minExponentDigits = fields.get("minExponentDigits", (byte) 0);

        int maximumIntegerDigits = fields.get("maximumIntegerDigits", 309);
        int minimumIntegerDigits = fields.get("minimumIntegerDigits", 309);
        int maximumFractionDigits = fields.get("maximumFractionDigits", 340);
        int minimumFractionDigits = fields.get("minimumFractionDigits", 340);
        this.serialVersionOnStream = fields.get("serialVersionOnStream", 0);

        Locale locale = (Locale) Format.getInternalField("locale", symbols);
        dform = new com.ibm.icu.text.DecimalFormat("",
                new com.ibm.icu.text.DecimalFormatSymbols(locale));
        setInternalField("useExponentialNotation", dform, Boolean
                .valueOf(useExponentialNotation));
        setInternalField("minExponentDigits", dform,
                new Byte(minExponentDigits));
        dform.setPositivePrefix(positivePrefix);
        dform.setPositiveSuffix(positiveSuffix);
        dform.setNegativePrefix(negativePrefix);
        dform.setNegativeSuffix(negativeSuffix);
        setInternalField("posPrefixPattern", dform, posPrefixPattern);
        setInternalField("posSuffixPattern", dform, posSuffixPattern);
        setInternalField("negPrefixPattern", dform, negPrefixPattern);
        setInternalField("negSuffixPattern", dform, negSuffixPattern);
        dform.setMultiplier(multiplier);
        dform.setGroupingSize(groupingSize);
        dform.setDecimalSeparatorAlwaysShown(decimalSeparatorAlwaysShown);
        dform.setMinimumIntegerDigits(minimumIntegerDigits);
        dform.setMaximumIntegerDigits(maximumIntegerDigits);
        dform.setMinimumFractionDigits(minimumFractionDigits);
        dform.setMaximumFractionDigits(maximumFractionDigits);
        this.setParseBigDecimal(parseBigDecimal);

        if (serialVersionOnStream < 3) {
            setMaximumIntegerDigits(super.getMaximumIntegerDigits());
            setMinimumIntegerDigits(super.getMinimumIntegerDigits());
            setMaximumFractionDigits(super.getMaximumFractionDigits());
            setMinimumFractionDigits(super.getMinimumFractionDigits());
        }
        if (serialVersionOnStream < 1) {
            this.setInternalField("useExponentialNotation", dform,
                    Boolean.FALSE);
        }
        serialVersionOnStream = 3;
    }

    /*
     * Copies decimal format symbols from text object to ICU one.
     *
     * @param icu the object which receives the new values. @param dfs the
     * object which contains the new values.
     */
    private void copySymbols(final com.ibm.icu.text.DecimalFormatSymbols icu,
            final DecimalFormatSymbols dfs) {
        Currency currency = dfs.getCurrency();
        if (currency == null) {
            icu.setCurrency(com.ibm.icu.util.Currency.getInstance("XXX")); //$NON-NLS-1$
        } else {
            icu.setCurrency(com.ibm.icu.util.Currency.getInstance(dfs
                    .getCurrency().getCurrencyCode()));
        }

        icu.setCurrencySymbol(dfs.getCurrencySymbol());
        icu.setDecimalSeparator(dfs.getDecimalSeparator());
        icu.setDigit(dfs.getDigit());
        icu.setGroupingSeparator(dfs.getGroupingSeparator());
        icu.setInfinity(dfs.getInfinity());
        icu
                .setInternationalCurrencySymbol(dfs
                        .getInternationalCurrencySymbol());
        icu.setMinusSign(dfs.getMinusSign());
        icu.setMonetaryDecimalSeparator(dfs.getMonetaryDecimalSeparator());
        icu.setNaN(dfs.getNaN());
        icu.setPatternSeparator(dfs.getPatternSeparator());
        icu.setPercent(dfs.getPercent());
        icu.setPerMill(dfs.getPerMill());
        icu.setZeroDigit(dfs.getZeroDigit());
    }

    /*
     * Sets private field value by reflection.
     *
     * @param fieldName the field name to be set @param target the object which
     * field to be set @param value the value to be set
     */
    private void setInternalField(final String fieldName, final Object target,
            final Object value) {
        AccessController
                .doPrivileged(new PrivilegedAction<java.lang.reflect.Field>() {
                    public java.lang.reflect.Field run() {
                        java.lang.reflect.Field field = null;
                        try {
                            field = target.getClass().getDeclaredField(
                                    fieldName);
                            field.setAccessible(true);
                            field.set(target, value);
                        } catch (Exception e) {
                            return null;
                        }
                        return field;
                    }
                });
    }
}


text:
id: reference
title: "Reference"
content-type: page
-----

This section provides some reference information related to the default metadata of contents and assets, as well as the full documentation of the [hastysite](class:kwd) min Module.

## Default Content and Asset Metadata

The following table lists all the default metadata properties available for contents and assets, and also after which build phase they become available.

> %note%
> Note
>
> You can define your own custom metadata for contents in a header section delimited by five dashes, at the start of each content file.

> %responsive%
> Property       | Content               | Asset
> ---------------|-----------------------|-----------------
> id             | [](class:check)       | [](class:check)
> path           | [](class:check)       | [](class:check)
> ext            | [](class:check)       | [](class:check)
> type           | [](class:check)       | [](class:check)
> title          | [](class:check)^1     | [](class:square)
> content-type   | [](class:check)^1     | [](class:square)
> date           | [](class:check)^(1,2) | [](class:square)
> timestamp      | [](class:check)^(1,2) | [](class:square)
> contents       | [](class:check)^3     | [](class:check)^3

> %unstyled%
> * 1 This property is defined for all **page** and **post** contents created using the default [page](class:kwd) and [post](class:kwd) commands.
> * 2 This property is defined for all **post** contents created using the default [post](class:kwd) command.
> * 3 This property *must* be added to contents and assets before they can be written to the output folder. This can be done implicitly using symbols provided with the [hastysite](class:kwd) min module.

## [hastysite](class:kwd) min Module

This [min](https://min-lang.org) module can be imported in the [rules.min](class:kwd) file or in any script file and can be used to perform common operations such as ready and writing files, and interact with HastySite data at build time.

{{null => ∅}}
{{d => [dict](class:kwd)}}
{{q => [quot](class:kwd)}}
{{m => [meta](class:kwd)}}
{{qm => [(meta\*)](class:kwd)}}
{{q1 => [quot1](class:kwd)}}
{{q2 => [quot2](class:kwd)}}
{{s => [string](class:kwd)}}
{{s1 => [string1](class:kwd)}}
{{s2 => [string2](class:kwd)}}

{#op =>

### [$1](class:kwd)

> %operator%
> [ $2 **⇒** $3](class:kwd)
>
> $4
 #}

{#op||assets||{{null}}||{{qm}}||
Returns a quotation of metadata dictionaries {{qm}} containing the metadata of each asset file.
 #}

{#op||clean-output||{{null}}||{{null}}||
Deletes all the contents of the [output](class:dir) directory.
 #}

{#op||clean-temp||{{null}}||{{null}}||
Deletes all the contents of the [temp](class:dir) directory.
 #}

{#op||contents||{{null}}||{{qm}}||
Returns a quotation of metadata dictionaries {{qm}} containing the metadata of each content file.
 #}

{#op||input-fread||{{m}}||{{s}}||
Reads the contents of the file identified by the metadata dictionary {{m}} (such as those returned by the [contents](class:kwd) and [assets](class:kwd) parameters).

Note that:

* The source directory is determined by the value of the [type](class:kwd) metadata property.
* The path within the source directory is determined by the value of the [path](class:kwd) metadata property.
 #}

{#op||markdown||{{s1}} {{d}}||{{s2}}||
Converts the [HastyScribe](https://h3rald.com/hastyscribe) Markdown string {{s1}} into the HTML fragment {{s2}}, using the properties of {{d}} as custom fields (accessible therefore via HastyScribe's [\{\{$<field-name>\}\}](class:kwd) syntax).
 #}

{#op||mustache||{{s1}} {{d}}||{{s2}}||
Renders mustache template {{s1}} into {{s2}}, using dictionary {{d}} as context.

> %note%
> Note
>
> {{s1}} is the path to the mustache template file, relative to the [templates](class:dir) directory and without [.mustache](class:ext).
 #}

{#op||output||{{null}}||{{s}}||
Returns the full path to the [output](class:dir) directory.
 #}

{#op||output-cp||{{m}}||{{null}}||
Copies a file from the source directory ([contents](class:dir) or [assets](class:dir) depending on its [type](class:kwd)) to the [output](class:dir) directory.

Note that:

* The source directory is determined by the value of the [type](class:kwd) metadata property.
* The path within the source directory is determined by the value of the [path](class:kwd) metadata property.
* The destination path within the output directory is determined by the value of concatenation of the [id](class:kwd) and [ext](class:kwd) metadata properties.
* The contents of the file are retrieved from the [contents](class:kwd) metadata property (in case of contents) or the contents of the original file (in case of assets).

 #}

{#op||output-fwrite||{{m}}||{{null}}||
Writes the contents of the file identified by the metadata dictionary {{m}} (such as those returned by the [contents](class:kwd) and [assets](class:kwd) parameters).

Note that:

* The destination path within the output directory is determined by the value of concatenation of the [id](class:kwd) and [ext](class:kwd) metadata properties.
* The contents of the file are retrieved from the [contents](class:kwd) metadata property (in case of contents) or the contents of the original file (in case of assets).

 #}

{#op||postprocess||{{null}}||{{null}}||
Starts the postprocessing phase of the build.
 #}

{#op||preprocess||{{null}}||{{null}}||
Starts the preprocessing phase of the build.
 #}

{#op||preprocess-css||{{s1}}||{{s2}}||
Pre-process CSS contents within {{s1}}, i.e.:

1. Pseudo-SCSS partial imports. Partial CSS files must start with an underscore and be placed in the `css-partials` directory (set in your [settings.json](class:file), or [assets/styles](class:dir) if not specified).
2. [CSS variable](https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_variables) declarations

Returns the resulting CSS code {{s2}}.

For example, the following CSS code in two different files:

\_vars.css:
: ```
  :root {
     --standard-gray: #cccccc;
  }
  ```

style.css:
: ```
  @import 'vars';
  .note {
    background-color: var(--standard-gray);
  }
  ```

Will be converted into the following:

```
:root {
  --standard-gray: #cccccc;
}

.note {
  background-color: #cccccc;
}
```

> %warning%
> Limitation
>
> Only basic support for CSS variables is provided, e.g. no fallback values are supported.
 #}

{#op||process-rules||{{null}}||{{null}}||
Starts the processing phase of the build, and interprets the [rules.min](class:file) file.
 #}

{#op||settings||{{null}}||{{d}}||
Returns a dictionary {{d}} containing all the settings defined in the [settings.json](class:file) file.
 #}


text:
Spontaneous.EventSource = (function($, S) {
	var EventSource = new JS.Singleton({
		eventSource: function() {
			if (!this._eventSource) {
				this._eventSource = new window.EventSource(S.Ajax.request_url('/events', true));
			}
			return this._eventSource;
		},

		addEventListener: function(event, callback) {
			this.eventSource().addEventListener(event, callback);
		},
		removeEventListener: function(event, callback) {
			this.eventSource().removeEventListener(event, callback);
		}
	});
	return EventSource;
})(jQuery, Spontaneous);


text:
<meta charset='utf-8'>

[Input Gesture]


text:
package yalantis.com.sidemenu.sample.fragment;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import yalantis.com.sidemenu.sample.R;

/**
 * Created by TheAppExperts on 20/10/2017.
 */

public class SecondFragment extends Fragment{
    private View containerView;
    TextView textView;

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        Log.d("Second Fragment", "onviewcreated");
        //this.containerView = view.findViewById(R.id.container);
        //Log.d("Second Fragment", "onviewcreated");

        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        Log.d("Second Fragment", "oncreateView");
        return rootView;
    }
}


text:
.. _payloadtype-com.apple.caldav.account:

CalDAV Payload
==============

.. figure:: /_static/ProfileManifests/Icons/ManifestsApple/com.apple.caldav.account.png
    :align: right
    :figwidth: 200px

:download:`Template </_static/examples/com.apple.caldav.account.mobileconfig>`

This payload configures a CalDAV account.

.. contents::

Summary
-------

.. pfmheader:: /_static/ProfileManifests/Manifests/ManifestsApple/com.apple.caldav.account.plist

Keys
----

.. pfmkey:: CalDAVAccountDescription /_static/ProfileManifests/Manifests/ManifestsApple/com.apple.caldav.account.plist
.. pfmkey:: CalDAVPort /_static/ProfileManifests/Manifests/ManifestsApple/com.apple.caldav.account.plist
.. pfmkey:: CalDAVHostName /_static/ProfileManifests/Manifests/ManifestsApple/com.apple.caldav.account.plist
.. pfmkey:: CalDAVUseSSL /_static/ProfileManifests/Manifests/ManifestsApple/com.apple.caldav.account.plist
.. pfmkey:: CalDAVPrincipalURL /_static/ProfileManifests/Manifests/ManifestsApple/com.apple.caldav.account.plist
.. pfmkey:: CalDAVUsername /_static/ProfileManifests/Manifests/ManifestsApple/com.apple.caldav.account.plist
.. pfmkey:: CalDAVPassword /_static/ProfileManifests/Manifests/ManifestsApple/com.apple.caldav.account.plist


text:
package ca.oson.json.gson.functional;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;

import junit.framework.TestCase;
import ca.oson.json.support.TestCaseBase;

import com.google.gson.Gson;

/**
 * Tests for ensuring Gson thread-safety.
 *
 * @author Inderjeet Singh
 * @author Joel Leitch
 */
public class ConcurrencyTest extends TestCaseBase {

  /**
   * Source-code based on
   * http://groups.google.com/group/google-gson/browse_thread/thread/563bb51ee2495081
   */
  public void testSingleThreadSerialization() {
    MyObject myObj = new MyObject();
    for (int i = 0; i < 10; i++) {
      oson.toJson(myObj);
    }
  }

  /**
   * Source-code based on
   * http://groups.google.com/group/google-gson/browse_thread/thread/563bb51ee2495081
   */
  public void testSingleThreadDeserialization() {
    for (int i = 0; i < 10; i++) {
      oson.fromJson("{'a':'hello','b':'world','i':1}", MyObject.class);
    }
  }

  /**
   * Source-code based on
   * http://groups.google.com/group/google-gson/browse_thread/thread/563bb51ee2495081
   */
  public void testMultiThreadSerialization() throws InterruptedException {
    final CountDownLatch startLatch = new CountDownLatch(1);
    final CountDownLatch finishedLatch = new CountDownLatch(10);
    final AtomicBoolean failed = new AtomicBoolean(false);
    ExecutorService executor = Executors.newFixedThreadPool(10);
    String expected = "{\"a\":\"hello\",\"b\":\"world\",\"i\":42}";
    for (int taskCount = 0; taskCount < 10; taskCount++) {
      executor.execute(new Runnable() {
        public void run() {
          MyObject myObj = new MyObject();
          try {
            startLatch.await();
            for (int i = 0; i < 10; i++) {
              String json = oson.toJson(myObj);
              assertEquals(expected, json);
            }
          } catch (Throwable t) {
            failed.set(true);
          } finally {
            finishedLatch.countDown();
          }
        }
      });
    }
    startLatch.countDown();
    finishedLatch.await();
    assertFalse(failed.get());
  }

  /**
   * Source-code based on
   * http://groups.google.com/group/google-gson/browse_thread/thread/563bb51ee2495081
   */
  public void testMultiThreadDeserialization() throws InterruptedException {
	  oson.clear();

    final CountDownLatch startLatch = new CountDownLatch(1);
    final CountDownLatch finishedLatch = new CountDownLatch(10);
    final AtomicBoolean failed = new AtomicBoolean(false);
    ExecutorService executor = Executors.newFixedThreadPool(10);
    for (int taskCount = 0; taskCount < 10; taskCount++) {
      executor.execute(new Runnable() {
        public void run() {
          try {
            startLatch.await();
            for (int i = 0; i < 10; i++) {
            	MyObject obj = oson.fromJson("{'a':'hello','b':'world','i':1}", MyObject.class);
            	assertTrue(obj instanceof MyObject);
            	assertEquals(obj.a, "hello");
            	assertEquals(obj.b, "world");
            	assertEquals(obj.i, 1);
            }
          } catch (Throwable t) {
            failed.set(true);
            t.printStackTrace();
          } finally {
            finishedLatch.countDown();
          }
        }
      });
    }
    startLatch.countDown();
    finishedLatch.await();
    assertFalse(failed.get());
  }

  @SuppressWarnings("unused")
  private static class MyObject {
    String a;
    String b;
    int i;

    MyObject() {
      this("hello", "world", 42);
    }

    public MyObject(String a, String b, int i) {
      this.a = a;
      this.b = b;
      this.i = i;
    }
  }
}


text:
<?php

/**
 *
 *
 * @author Komov Roman
 */
class BaseHttpRequest extends CHttpRequest
{

    public function getJsonData()
    {
        $request_body=$this->getRawBody();

        $json= CJSON::decode($request_body);

        Yii::log(json_encode($json,JSON_PRETTY_PRINT));

        return $json;
    }
}


text:
declare function _exports(moduleId: TODO, options: TODO): TODO;
export = _exports;
export type TODO = any;


text:
module API
  class Root < Grape::API
    mount V1::Root
  end
end