text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.redkalex.source.pgsql;

import java.io.Serializable;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import static java.nio.charset.StandardCharsets.UTF_8;
import java.time.*;
import java.time.format.*;
import static java.time.format.DateTimeFormatter.*;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.atomic.*;
import org.redkale.convert.json.JsonConvert;
import org.redkale.source.EntityInfo;
import org.redkale.util.*;

/**
 *
 * @author zhangjx
 */
public abstract class PgsqlFormatter {

    //attr为空就返回byte[], 不为空返回attr对应类型的对象
    public static <T> Serializable decodeRowColumnValue(ByteBuffer buffer, ByteArray tmp, Attribute<T, Serializable> attr, int bslen) {
        if (bslen == -1) return null;
        if (attr == null) {
            byte[] bs = new byte[bslen];
            buffer.get(bs);
            return bs;
        }
        Class type = attr.type();
        if (type == int.class || type == Integer.class) {
            return buffer.getInt();
        } else if (type == String.class) {
            if (bslen == 0) return "";
            tmp.clear().put(buffer, bslen);
            return tmp.toString(StandardCharsets.UTF_8);
        } else if (type == long.class || type == Long.class) {
            return buffer.getLong();
        } else if (type == boolean.class || type == Boolean.class) {
            return buffer.get() == 1;
        } else if (type == short.class || type == Short.class) {
            return buffer.getShort();
        } else if (type == float.class || type == Float.class) {
            return Float.intBitsToFloat(buffer.getInt());
        } else if (type == double.class || type == Double.class) {
            return Double.longBitsToDouble(buffer.getLong());
        } else if (type == byte[].class) {
            byte[] bs = new byte[bslen];
            buffer.get(bs);
            return bs;
        } else if (type == AtomicInteger.class) {
            return new AtomicInteger(buffer.getInt());
        } else if (type == AtomicLong.class) {
            return new AtomicLong(buffer.getLong());
        } else if (type == byte.class || type == Byte.class) {
            return buffer.get();
        } else if (type == char.class || type == Character.class) {
            return buffer.getChar();
        } else if (type == java.sql.Date.class) {
            return new java.sql.Date(LOCAL_DATE_EPOCH.plus(buffer.getInt(), ChronoUnit.DAYS).toEpochSecond(LocalTime.MIN, ZoneOffset.UTC) * 1000);
        } else if (type == java.util.Date.class) {
            return new java.util.Date(LOCAL_DATE_EPOCH.plus(buffer.getInt(), ChronoUnit.DAYS).toEpochSecond(LocalTime.MIN, ZoneOffset.UTC) * 1000);
        } else if (type == java.time.LocalDate.class) {
            return LOCAL_DATE_EPOCH.plus(buffer.getInt(), ChronoUnit.DAYS);
        } else if (type == java.time.LocalTime.class) {
            return LocalTime.ofNanoOfDay(buffer.getLong() * 1000);
        } else {
            if (bslen == 0) return null;
            tmp.clear().put(buffer, bslen);
            return JsonConvert.root().convertFrom(attr.genericType(), tmp.toString(StandardCharsets.UTF_8));
            //throw new RuntimeException("Not supported column: " + attr.field() + ", type: " + attr.type());
        }
    }

    public static <T> void encodePrepareParamValue(ByteArray array, EntityInfo<T> info, boolean binary, Attribute<T, Serializable> attr, Object param) {
        byte[] bs = formatPrepareParamText(info, attr, param);
        if (bs == null) {
            array.putInt(-1);
        } else {
            array.putInt(bs.length);
            array.put(bs);
        }
    }

    //--------------------------------- binary -----------------------------
    //---------------------------------- text ------------------------------
    private static <T> byte[] formatPrepareParamText(EntityInfo<T> info, Attribute<T, Serializable> attr, Object param) {
        if (param == null && info.isNotNullJson(attr)) return new byte[0];
        if (param == null) return null;
        if (param instanceof byte[]) return (byte[]) param;
        if (param instanceof Boolean) return (Boolean) param ? TRUE_BYTES : FALSE_BYTES;
        if (param instanceof java.sql.Date) return ISO_LOCAL_DATE.format(((java.sql.Date) param).toLocalDate()).getBytes(UTF_8);
        if (param instanceof java.sql.Time) return ISO_LOCAL_TIME.format(((java.sql.Time) param).toLocalTime()).getBytes(UTF_8);
        if (param instanceof java.sql.Timestamp) return TIMESTAMP_FORMAT.format(((java.sql.Timestamp) param).toLocalDateTime()).getBytes(UTF_8);
        if (param instanceof java.time.LocalDate) return ISO_LOCAL_DATE.format((java.time.LocalDate) param).getBytes(UTF_8);
        if (param instanceof java.time.LocalTime) return ISO_LOCAL_TIME.format((java.time.LocalTime) param).getBytes(UTF_8);
        if (param instanceof java.time.LocalDateTime) return TIMESTAMP_FORMAT.format((java.time.LocalDateTime) param).getBytes(UTF_8);
        if (!(param instanceof Number) && !(param instanceof CharSequence) && !(param instanceof java.util.Date)
            && !param.getClass().getName().startsWith("java.sql.") && !param.getClass().getName().startsWith("java.time.")) {
            if (attr == null) return info.getJsonConvert().convertTo(param).getBytes(StandardCharsets.UTF_8);
            return info.getJsonConvert().convertTo(attr.genericType(), param).getBytes(StandardCharsets.UTF_8);
        }
        return String.valueOf(param).getBytes(UTF_8);
    }

    static final byte[] TRUE_BYTES = new byte[]{'t'};

    static final byte[] FALSE_BYTES = new byte[]{'f'};

    static final DateTimeFormatter TIMESTAMP_FORMAT = new DateTimeFormatterBuilder().parseCaseInsensitive().append(ISO_LOCAL_DATE).appendLiteral(' ').append(ISO_LOCAL_TIME).toFormatter();

    static final DateTimeFormatter TIMESTAMPZ_FORMAT = new DateTimeFormatterBuilder().parseCaseInsensitive().append(ISO_LOCAL_DATE).appendLiteral(' ').append(ISO_LOCAL_TIME).appendOffset("+HH:mm", "").toFormatter();

    static final DateTimeFormatter TIMEZ_FORMAT = new DateTimeFormatterBuilder().parseCaseInsensitive().append(ISO_LOCAL_TIME).appendOffset("+HH:mm", "").toFormatter();

    static final LocalDate LOCAL_DATE_EPOCH = LocalDate.of(2000, 1, 1);

    static final LocalDateTime LOCAL_DATE_TIME_EPOCH = LocalDateTime.of(2000, 1, 1, 0, 0, 0);

    static final OffsetDateTime OFFSET_DATE_TIME_EPOCH = LocalDateTime.of(2000, 1, 1, 0, 0, 0).atOffset(ZoneOffset.UTC);
}


text:
package com.e_gineering.micro.playground.security.entity;

import java.io.Serializable;
import java.util.Collections;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import javax.persistence.Basic;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

@Entity
@Table(schema = "security", name = "caller")
@NamedQueries({
    @NamedQuery(name = "Caller.findByUsername", query = "SELECT c FROM Caller c WHERE LOWER(c.username) = LOWER(:username)")
})
public class Caller implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @SequenceGenerator(schema = "security", name = "caller_seq", sequenceName = "caller_seq", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "caller_seq")
    @Column(name = "id", nullable = false)
    private Long id;

    @Basic(optional = false)
    @Column(name = "username", nullable = false, length = 255, unique = true)
    private String username;

    @Basic(optional = false)
    @Column(name = "password", nullable = false, length = 255)
    private String password;

    @ElementCollection(fetch = FetchType.EAGER)
    @CollectionTable(schema = "security", name = "caller_role", joinColumns = {@JoinColumn(name = "caller_id", referencedColumnName = "id")})
    @Column(name = "role", nullable = false)
    private Set<String> roles = new HashSet<>();

    protected Caller() {
    }

    public Caller(final String username, final String password) {
        if (null == username || username.trim().isEmpty()) {
            throw new IllegalArgumentException("Username must be a non-null, non-blank value");
        }

        this.username = username.trim();
        this.password = password;
    }

    public Long getId() {
        return id;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(final String password) {
        this.password = password;
    }

    public Set<String> getRoles() {
        return Collections.unmodifiableSet(roles);
    }

    public boolean addRole(final String role) {
        return roles.add(Objects.requireNonNull(role));
    }

    public boolean removeRole(final String role) {
        return roles.remove(Objects.requireNonNull(role));
    }

    @Override
    public int hashCode() {
        int hash = 5;
        hash = 29 * hash + Objects.hashCode(this.username);
        return hash;
    }

    @Override
    public boolean equals(final Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Caller other = (Caller) obj;
        return Objects.equals(this.username, other.username);
    }

}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
  PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<meta name="copyright" content="(C) Copyright 2014" />
<meta name="DC.rights.owner" content="(C) Copyright 2014" />
<meta name="DC.Type" content="topic" />
<meta name="DC.Title" content="topic c" />
<meta name="DC.Source" content="a1.dita" />
<meta name="DC.Relation" scheme="URI" content="dita1.html" />
<meta name="DC.Relation" scheme="URI" content="a1.html" />
<meta name="DC.Relation" scheme="URI" content="abs.html" />
<meta name="DC.Creator" content="" />
<meta name="DC.Publisher" content="" />
<meta name="DC.Format" content="XHTML" />
<meta name="DC.Identifier" content="c" />
<link rel="stylesheet" type="text/css" href="commonltr.css" />
<title>topic c</title>

topic c

key "abs" defines a term, surface form, and acronym.

xref reference to abs, should be full term: Anti-lock Braking System

keyword reference to abs, should be full term: Anti-lock Braking System

Term reference to abs, should be surface form: <dfn class="term">Anti-lock Braking System (ABS)</dfn>

First abbreviated form to abs, should be acronym: <dfn class="term abbreviated-form">ABS</dfn>

key "a" reference to a topic

xref reference to a:topic a1

keyword reference to a:topic a1

Term reference to a:<dfn class="term">TERM REF A</dfn>

conkeyref

        Fruit bats need just a little tender-loving care each day.

        Ensuring that your bat is happy and content will give you many unending
        days and nights of wonderful rewards.

Define a keyword,which content is "KEYWORD"

term pulls keyword: <dfn class="term">KEYWORD</dfn>

keyword pulls keyword: KEYWORD

ph tag could has the attribute "keyref"

ph reference to a:topic a1

ph reference to abs:Anti-lock Braking System

ph reference to keyword:KEYWORD

dt tag could has the attribute "keyref"

keyref a

...........................

keyref abs

...........................

keyref keyword

...........................

image tag could has the attribute "keyref"

cite tag could has the attribute "keyref"

The keyref a: topic a1

The keyref abs: Anti-lock Braking System

The keyref keyword: KEYWORD

lq  tag could has the attribute "keyref"

.....................

a1.dita

.....................

abs.dita

.....................

Related concepts

Anti-lock Braking System

Related information

DITA1

topic a1


text:
describe('native log objects', function () {
    'use strict';

    var preservedConsoleLog;
    var logger;
    var logArg1;
    var logArg2;
    var logArg3;

    beforeEach(function () {
        logArg1 = '';
        logArg2 = '';
        logArg3 = '';
        preservedConsoleLog = console.log;

        // overwrite console log so we can spy on it
        console.log = function (arg1, arg2, arg3) {
            logArg1 = arg1;
            logArg2 = arg2;
            logArg3 = arg3;
        };
    });

    afterEach(function () {
        console.log = preservedConsoleLog;
    });

    describe('disabled color', function () {
        beforeEach(function () {
            logger = new Logger({
                logLevel: 'debug',
                colorMode: false,
                timeStamp: false,
                nativeLog: true
            });
        });

        it('should be able to log an object', function () {
            logger.log('error', {foo: 'bar'});

            expect('[ERROR]: ').toEqual(logArg1);
            expect({foo: 'bar'}).toEqual(logArg2);
        });

        it('should be able to log an array', function () {
            logger.log('error', ['foo', 'bar']);

            expect('[ERROR]: ').toEqual(logArg1);
            expect(['foo', 'bar']).toEqual(logArg2);
        });

        it('should be able to log a function', function () {
            var errorFn = function () {};

            logger.log('error', errorFn);

            expect('[ERROR]: ').toEqual(logArg1);
            expect(errorFn).toEqual(logArg2);
        });
    });

    describe('enabled color', function () {
        beforeEach(function () {
            logger = new Logger({
                logLevel: 'debug',
                colorMode: true,
                timeStamp: false,
                nativeLog: true
            });
        });

        it('should be able to log an object', function () {
            logger.log('error', {foo: 'bar'});

            expect('%c[ERROR]: ').toEqual(logArg1);
            expect('color: #FF0000').toEqual(logArg2);
            expect({foo: 'bar'}).toEqual(logArg3);
        });

        it('should be able to log an array', function () {
            logger.log('error', ['foo', 'bar']);

            expect('%c[ERROR]: ').toEqual(logArg1);
            expect('color: #FF0000').toEqual(logArg2);
            expect(['foo', 'bar']).toEqual(logArg3);
        });

        it('should be able to log a function', function () {
            var errorFn = function () {};

            logger.log('error', errorFn);

            expect('%c[ERROR]: ').toEqual(logArg1);
            expect('color: #FF0000').toEqual(logArg2);
            expect(errorFn).toEqual(logArg3);
        });
    });

    describe('disabled color and shortcuts', function () {
        beforeEach(function () {
            logger = new Logger({
                logLevel: 'debug',
                colorMode: false,
                timeStamp: false,
                nativeLog: true
            });
        });

        it('should be able to log an object', function () {
            logger.error({foo: 'bar'});

            expect('[ERROR]: ').toEqual(logArg1);
            expect({foo: 'bar'}).toEqual(logArg2);
        });

        it('should be able to log an array', function () {
            logger.error(['foo', 'bar']);

            expect('[ERROR]: ').toEqual(logArg1);
            expect(['foo', 'bar']).toEqual(logArg2);
        });

        it('should be able to log a function', function () {
            var errorFn = function () {};

            logger.error(errorFn);

            expect('[ERROR]: ').toEqual(logArg1);
            expect(errorFn).toEqual(logArg2);
        });
    });

    describe('enabled color and shortcuts', function () {
        beforeEach(function () {
            logger = new Logger({
                logLevel: 'debug',
                colorMode: true,
                timeStamp: false,
                nativeLog: true
            });
        });

        it('should be able to log an object', function () {
            logger.error({foo: 'bar'});

            expect('%c[ERROR]: ').toEqual(logArg1);
            expect('color: #FF0000').toEqual(logArg2);
            expect({foo: 'bar'}).toEqual(logArg3);
        });

        it('should be able to log an array', function () {
            logger.error(['foo', 'bar']);

            expect('%c[ERROR]: ').toEqual(logArg1);
            expect('color: #FF0000').toEqual(logArg2);
            expect(['foo', 'bar']).toEqual(logArg3);
        });

        it('should be able to log a function', function () {
            var errorFn = function () {};

            logger.error(errorFn);

            expect('%c[ERROR]: ').toEqual(logArg1);
            expect('color: #FF0000').toEqual(logArg2);
            expect(errorFn).toEqual(logArg3);
        });
    });
});


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#pragma once

#include <vespa/searchlib/query/base.h>
#include <vespa/vespalib/objects/nbostream.h>
#include <vespa/vespalib/util/stringfmt.h>

namespace proton {

/**
 * Class used to localize a local document id inside a sub document db.
 */
class DbDocumentId {
private:
    uint32_t            _subDbId; // sub document db id
    search::DocumentIdT _lid;     // local document id
public:
    DbDocumentId() noexcept: DbDocumentId(0) {}
    DbDocumentId(search::DocumentIdT lid) noexcept : DbDocumentId(0, lid) {}
    DbDocumentId(uint32_t subDbId, search::DocumentIdT lid) noexcept
        : _subDbId(subDbId),
          _lid(lid)
    { }
    uint32_t getSubDbId() const { return _subDbId; }
    search::DocumentIdT getLid() const { return _lid; }
    bool valid() const { return _lid != 0; }

    bool
    operator!=(const DbDocumentId &rhs) const
    {
        return _subDbId != rhs._subDbId ||
                   _lid != rhs._lid;
    }

    bool
    operator==(const DbDocumentId &rhs) const
    {
        return _subDbId == rhs._subDbId &&
                   _lid == rhs._lid;
    }

    vespalib::string toString() const {
        return vespalib::make_string("subDbId=%u, lid=%u", _subDbId, _lid);
    }

    friend vespalib::nbostream &
    operator<<(vespalib::nbostream &os, const DbDocumentId &dbdId);

    friend vespalib::nbostream &
    operator>>(vespalib::nbostream &is, DbDocumentId &dbdId);
};

} // namespace proton


text:
package fr.openwide.core.wicket.more.markup.html.template.js.jquery.plugins.placeholderpolyfill;

import org.apache.wicket.Component;
import org.apache.wicket.behavior.Behavior;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.JavaScriptHeaderItem;
import org.apache.wicket.markup.head.OnDomReadyHeaderItem;
import org.wicketstuff.wiquery.core.javascript.JsStatement;

public class PlaceholderPolyfillBehavior extends Behavior {

	private static final long serialVersionUID = 468977788703981632L;

	private static final String PLACEHOLDER = "placeholder";

	private static final String PLACEHOLDER_DISABLE = "OWSI.PlaceholderUtils.disable";

	private static final String DEFAULT_SELECTOR = "[placeholder]";

	public PlaceholderPolyfillBehavior() {
		super();
	}

	@Override
	public void renderHead(Component component, IHeaderResponse response) {
		response.render(JavaScriptHeaderItem.forReference(PlaceholderPolyfillJavaScriptResourceReference.get()));
		response.render(JavaScriptHeaderItem.forReference(PlaceholderPolyfillOpenwideJavaScriptResourceReference.get()));
		response.render(OnDomReadyHeaderItem.forScript(statement().render()));
	}

	/**
	 * Made available for use after ajax refreshes.
	 */
	public static JsStatement statement() {
		return new JsStatement().$(null, DEFAULT_SELECTOR).chain(PLACEHOLDER);
	}

	/**
	 * Made available for use before ajax refreshes.
	 */
	public static JsStatement disable() {
		return new JsStatement().$(null, DEFAULT_SELECTOR).append(".each(" + PLACEHOLDER_DISABLE + ")");
	}
}


text:
package com.wesleyhome.math;

import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;

class StringExpressionBeanTest {

    @Test
    void testValueBean() {
        ValueBeanOne valueBean = new ValueBeanOne();
        String expression = "(one + two) * zero";
        Number number = StringExpression.evaluateBean(expression, valueBean);
        assertThat(number).isEqualTo(0);
    }

    @Test
    void testValueBeanDotSyntax() {
        ValueBeanOne valueBean = new ValueBeanOne();
        String expression = "(oneHolder_one + two) * zero";
        Number number = StringExpression.evaluateBean(expression, valueBean);
        assertThat(number).isEqualTo(0);
    }
}


text:
package deliver

import (
	"context"
	"crypto/sha256"
	"crypto/tls"
	"crypto/x509"
	"net"
	"sync/atomic"
	"testing"
	"time"

	"github.com/golang/protobuf/proto"
	"github.com/hyperledger/fabric-protos-go/common"
	"github.com/hyperledger/fabric/internal/pkg/comm"
	"github.com/hyperledger/fabric/internal/pkg/comm/testpb"
	"github.com/hyperledger/fabric/protoutil"
	"github.com/stretchr/testify/require"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
)

func TestBindingInspectorBadInit(t *testing.T) {
	require.Panics(t, func() { NewBindingInspector(false, nil) })
}

func TestNoopBindingInspector(t *testing.T) {
	extract := func(msg proto.Message) []byte {
		return nil
	}
	require.Nil(t, NewBindingInspector(false, extract)(context.Background(), &common.Envelope{}))
	err := NewBindingInspector(false, extract)(context.Background(), nil)
	require.Error(t, err)
	require.Equal(t, "message is nil", err.Error())
}

func TestBindingInspector(t *testing.T) {
	lis, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		t.Fatalf("failed to create listener for test server: %v", err)
	}

	extract := func(msg proto.Message) []byte {
		env, isEnvelope := msg.(*common.Envelope)
		if !isEnvelope || env == nil {
			return nil
		}
		ch, err := protoutil.ChannelHeader(env)
		if err != nil {
			return nil
		}
		return ch.TlsCertHash
	}
	srv := newInspectingServer(lis, NewBindingInspector(true, extract))
	go srv.Start()
	defer srv.Stop()
	time.Sleep(time.Second)

	// Scenario I: Invalid header sent
	err = srv.newInspection(t).inspectBinding(nil)
	require.Error(t, err)
	require.Contains(t, err.Error(), "client didn't include its TLS cert hash")

	// Scenario II: invalid channel header
	ch, _ := proto.Marshal(protoutil.MakeChannelHeader(common.HeaderType_CONFIG, 0, "test", 0))
	// Corrupt channel header
	ch = append(ch, 0)
	err = srv.newInspection(t).inspectBinding(envelopeWithChannelHeader(ch))
	require.Error(t, err)
	require.Contains(t, err.Error(), "client didn't include its TLS cert hash")

	// Scenario III: No TLS cert hash in envelope
	chanHdr := protoutil.MakeChannelHeader(common.HeaderType_CONFIG, 0, "test", 0)
	ch, _ = proto.Marshal(chanHdr)
	err = srv.newInspection(t).inspectBinding(envelopeWithChannelHeader(ch))
	require.Error(t, err)
	require.Contains(t, err.Error(), "client didn't include its TLS cert hash")

	// Scenario IV: Client sends its TLS cert hash as needed, but doesn't use mutual TLS
	cert, _ := tls.X509KeyPair([]byte(selfSignedCertPEM), []byte(selfSignedKeyPEM))
	h := sha256.New()
	h.Write([]byte(cert.Certificate[0]))
	chanHdr.TlsCertHash = h.Sum(nil)
	ch, _ = proto.Marshal(chanHdr)
	err = srv.newInspection(t).inspectBinding(envelopeWithChannelHeader(ch))
	require.Error(t, err)
	require.Contains(t, err.Error(), "client didn't send a TLS certificate")

	// Scenario V: Client uses mutual TLS but sends the wrong TLS cert hash
	chanHdr.TlsCertHash = []byte{1, 2, 3}
	chHdrWithWrongTLSCertHash, _ := proto.Marshal(chanHdr)
	err = srv.newInspection(t).withMutualTLS().inspectBinding(envelopeWithChannelHeader(chHdrWithWrongTLSCertHash))
	require.Error(t, err)
	require.Contains(t, err.Error(), "claimed TLS cert hash is [1 2 3] but actual TLS cert hash is")

	// Scenario VI: Client uses mutual TLS and also sends the correct TLS cert hash
	err = srv.newInspection(t).withMutualTLS().inspectBinding(envelopeWithChannelHeader(ch))
	require.NoError(t, err)
}

type inspectingServer struct {
	addr string
	*comm.GRPCServer
	lastContext atomic.Value
	inspector   BindingInspector
}

func (is *inspectingServer) EmptyCall(ctx context.Context, _ *testpb.Empty) (*testpb.Empty, error) {
	is.lastContext.Store(ctx)
	return &testpb.Empty{}, nil
}

func (is *inspectingServer) inspect(envelope *common.Envelope) error {
	return is.inspector(is.lastContext.Load().(context.Context), envelope)
}

func newInspectingServer(listener net.Listener, inspector BindingInspector) *inspectingServer {
	srv, err := comm.NewGRPCServerFromListener(listener, comm.ServerConfig{
		ConnectionTimeout: 250 * time.Millisecond,
		SecOpts: comm.SecureOptions{
			UseTLS:      true,
			Certificate: []byte(selfSignedCertPEM),
			Key:         []byte(selfSignedKeyPEM),
		},
	})
	if err != nil {
		panic(err)
	}
	is := &inspectingServer{
		addr:       listener.Addr().String(),
		GRPCServer: srv,
		inspector:  inspector,
	}
	testpb.RegisterTestServiceServer(srv.Server(), is)
	return is
}

type inspection struct {
	tlsConfig *tls.Config
	server    *inspectingServer
	creds     credentials.TransportCredentials
	t         *testing.T
}

func (is *inspectingServer) newInspection(t *testing.T) *inspection {
	tlsConfig := &tls.Config{
		RootCAs: x509.NewCertPool(),
	}
	tlsConfig.RootCAs.AppendCertsFromPEM([]byte(selfSignedCertPEM))
	return &inspection{
		server:    is,
		creds:     credentials.NewTLS(tlsConfig),
		t:         t,
		tlsConfig: tlsConfig,
	}
}

func (ins *inspection) withMutualTLS() *inspection {
	cert, err := tls.X509KeyPair([]byte(selfSignedCertPEM), []byte(selfSignedKeyPEM))
	require.NoError(ins.t, err)
	ins.tlsConfig.Certificates = []tls.Certificate{cert}
	ins.creds = credentials.NewTLS(ins.tlsConfig)
	return ins
}

func (ins *inspection) inspectBinding(envelope *common.Envelope) error {
	ctx := context.Background()
	ctx, c := context.WithTimeout(ctx, time.Second*3)
	defer c()
	conn, err := grpc.DialContext(ctx, ins.server.addr, grpc.WithTransportCredentials(ins.creds), grpc.WithBlock())
	require.NoError(ins.t, err)
	defer conn.Close()
	_, err = testpb.NewTestServiceClient(conn).EmptyCall(context.Background(), &testpb.Empty{})
	require.NoError(ins.t, err)
	return ins.server.inspect(envelope)
}

func envelopeWithChannelHeader(ch []byte) *common.Envelope {
	pl := &common.Payload{
		Header: &common.Header{
			ChannelHeader: ch,
		},
	}
	payload, _ := proto.Marshal(pl)
	return &common.Envelope{
		Payload: payload,
	}
}

// Embedded certificates for testing
// The self-signed cert expires in 2028
var selfSignedKeyPEM = `-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIMLemLh3+uDzww1pvqP6Xj2Z0Kc6yqf3RxyfTBNwRuuyoAoGCCqGSM49
AwEHoUQDQgAEDB3l94vM7EqKr2L/vhqU5IsEub0rviqCAaWGiVAPp3orb/LJqFLS
yo/k60rhUiir6iD4S4pb5TEb2ouWylQI3A==
-----END EC PRIVATE KEY-----
`

var selfSignedCertPEM = `-----BEGIN CERTIFICATE-----
MIIBdDCCARqgAwIBAgIRAKCiW5r6W32jGUn+l9BORMAwCgYIKoZIzj0EAwIwEjEQ
MA4GA1UEChMHQWNtZSBDbzAeFw0xODA4MjExMDI1MzJaFw0yODA4MTgxMDI1MzJa
MBIxEDAOBgNVBAoTB0FjbWUgQ28wWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAQM
HeX3i8zsSoqvYv++GpTkiwS5vSu+KoIBpYaJUA+neitv8smoUtLKj+TrSuFSKKvq
IPhLilvlMRvai5bKVAjco1EwTzAOBgNVHQ8BAf8EBAMCBaAwEwYDVR0lBAwwCgYI
KwYBBQUHAwEwDAYDVR0TAQH/BAIwADAaBgNVHREEEzARgglsb2NhbGhvc3SHBH8A
AAEwCgYIKoZIzj0EAwIDSAAwRQIgOaYc3pdGf2j0uXRyvdBJq2PlK9FkgvsUjXOT
bQ9fWRkCIQCr1FiRRzapgtrnttDn3O2fhLlbrw67kClzY8pIIN42Qw==
-----END CERTIFICATE-----
`


text:
package com.google.cloud.dataflow.sdk.io;

import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.hasItem;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

import com.google.cloud.dataflow.sdk.coders.AvroCoder;
import com.google.cloud.dataflow.sdk.coders.DefaultCoder;
import com.google.cloud.dataflow.sdk.io.AvroIO.Write.Bound;
import com.google.cloud.dataflow.sdk.runners.DirectPipeline;
import com.google.cloud.dataflow.sdk.testing.DataflowAssert;
import com.google.cloud.dataflow.sdk.testing.TestPipeline;
import com.google.cloud.dataflow.sdk.transforms.Create;
import com.google.cloud.dataflow.sdk.transforms.display.DataflowDisplayDataEvaluator;
import com.google.cloud.dataflow.sdk.transforms.display.DisplayData;
import com.google.cloud.dataflow.sdk.transforms.display.DisplayDataEvaluator;
import com.google.cloud.dataflow.sdk.util.IOChannelUtils;
import com.google.cloud.dataflow.sdk.values.PCollection;
import com.google.common.base.MoreObjects;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterators;

import org.apache.avro.Schema;
import org.apache.avro.file.DataFileReader;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.reflect.Nullable;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * Tests for AvroIO Read and Write transforms.
 */
@RunWith(JUnit4.class)
public class AvroIOTest {
  @Rule
  public TemporaryFolder tmpFolder = new TemporaryFolder();

  @Test
  public void testReadWithoutValidationFlag() throws Exception {
    AvroIO.Read.Bound<GenericRecord> read = AvroIO.Read.from("gs://bucket/foo*/baz");
    assertTrue(read.needsValidation());
    assertFalse(read.withoutValidation().needsValidation());
  }

  @Test
  public void testWriteWithoutValidationFlag() throws Exception {
    AvroIO.Write.Bound<GenericRecord> write = AvroIO.Write.to("gs://bucket/foo/baz");
    assertTrue(write.needsValidation());
    assertFalse(write.withoutValidation().needsValidation());
  }

  @Test
  public void testAvroIOGetName() {
    assertEquals("AvroIO.Read", AvroIO.Read.from("gs://bucket/foo*/baz").getName());
    assertEquals("AvroIO.Write", AvroIO.Write.to("gs://bucket/foo/baz").getName());
    assertEquals("ReadMyFile",
        AvroIO.Read.named("ReadMyFile").from("gs://bucket/foo*/baz").getName());
    assertEquals("WriteMyFile",
        AvroIO.Write.named("WriteMyFile").to("gs://bucket/foo/baz").getName());
  }

  @DefaultCoder(AvroCoder.class)
  static class GenericClass {
    int intField;
    String stringField;
    public GenericClass() {}
    public GenericClass(int intValue, String stringValue) {
      this.intField = intValue;
      this.stringField = stringValue;
    }
    @Override
    public String toString() {
      return MoreObjects.toStringHelper(getClass())
          .add("intField", intField)
          .add("stringField", stringField)
          .toString();
    }
    @Override
    public int hashCode() {
      return Objects.hash(intField, stringField);
    }
    @Override
    public boolean equals(Object other) {
      if (other == null || !(other instanceof GenericClass)) {
        return false;
      }
      GenericClass o = (GenericClass) other;
      return Objects.equals(intField, o.intField) && Objects.equals(stringField, o.stringField);
    }
  }

  @Test
  public void testAvroIOWriteAndReadASingleFile() throws Throwable {
    DirectPipeline p = DirectPipeline.createForTest();
    List<GenericClass> values = ImmutableList.of(new GenericClass(3, "hi"),
        new GenericClass(5, "bar"));
    File outputFile = tmpFolder.newFile("output.avro");

    p.apply(Create.of(values))
      .apply(AvroIO.Write.to(outputFile.getAbsolutePath())
          .withoutSharding()
          .withSchema(GenericClass.class));
    p.run();

    p = DirectPipeline.createForTest();
    PCollection<GenericClass> input = p
        .apply(AvroIO.Read.from(outputFile.getAbsolutePath()).withSchema(GenericClass.class));

    DataflowAssert.that(input).containsInAnyOrder(values);
    p.run();
  }

  @DefaultCoder(AvroCoder.class)
  static class GenericClassV2 {
    int intField;
    String stringField;
    @Nullable String nullableField;
    public GenericClassV2() {}
    public GenericClassV2(int intValue, String stringValue, String nullableValue) {
      this.intField = intValue;
      this.stringField = stringValue;
      this.nullableField = nullableValue;
    }
    @Override
    public String toString() {
      return MoreObjects.toStringHelper(getClass())
          .add("intField", intField)
          .add("stringField", stringField)
          .add("nullableField", nullableField)
          .toString();
    }
    @Override
    public int hashCode() {
      return Objects.hash(intField, stringField, nullableField);
    }
    @Override
    public boolean equals(Object other) {
      if (other == null || !(other instanceof GenericClassV2)) {
        return false;
      }
      GenericClassV2 o = (GenericClassV2) other;
      return Objects.equals(intField, o.intField)
          && Objects.equals(stringField, o.stringField)
          && Objects.equals(nullableField, o.nullableField);
    }
  }

  /**
   * Tests that {@code AvroIO} can read an upgraded version of an old class, as long as the
   * schema resolution process succeeds. This test covers the case when a new, {@code @Nullable}
   * field has been added.
   *
   * <p>For more information, see http://avro.apache.org/docs/1.7.7/spec.html#Schema+Resolution
   */
  @Test
  public void testAvroIOWriteAndReadSchemaUpgrade() throws Throwable {
    DirectPipeline p = DirectPipeline.createForTest();
    List<GenericClass> values = ImmutableList.of(new GenericClass(3, "hi"),
        new GenericClass(5, "bar"));
    File outputFile = tmpFolder.newFile("output.avro");

    p.apply(Create.of(values))
      .apply(AvroIO.Write.to(outputFile.getAbsolutePath())
          .withoutSharding()
          .withSchema(GenericClass.class));
    p.run();

    List<GenericClassV2> expected = ImmutableList.of(new GenericClassV2(3, "hi", null),
        new GenericClassV2(5, "bar", null));
    p = DirectPipeline.createForTest();
    PCollection<GenericClassV2> input = p
        .apply(AvroIO.Read.from(outputFile.getAbsolutePath()).withSchema(GenericClassV2.class));

    DataflowAssert.that(input).containsInAnyOrder(expected);
    p.run();
  }

  @SuppressWarnings("deprecation") // using AvroCoder#createDatumReader for tests.
  private void runTestWrite(String[] expectedElements, int numShards) throws IOException {
    File baseOutputFile = new File(tmpFolder.getRoot(), "prefix");
    String outputFilePrefix = baseOutputFile.getAbsolutePath();
    TestPipeline p = TestPipeline.create();
    Bound<String> write = AvroIO.Write.to(outputFilePrefix).withSchema(String.class);
    if (numShards > 1) {
      write = write.withNumShards(numShards);
    } else {
      write = write.withoutSharding();
    }
    p.apply(Create.<String>of(expectedElements)).apply(write);
    p.run();

    String shardNameTemplate = write.getShardNameTemplate();

    assertTestOutputs(expectedElements, numShards, outputFilePrefix, shardNameTemplate);
  }

  public static void assertTestOutputs(
      String[] expectedElements, int numShards, String outputFilePrefix, String shardNameTemplate)
      throws IOException {
    // Validate that the data written matches the expected elements in the expected order
    List<File> expectedFiles = new ArrayList<>();
    for (int i = 0; i < numShards; i++) {
      expectedFiles.add(
          new File(
              IOChannelUtils.constructName(
                  outputFilePrefix, shardNameTemplate, "" /* no suffix */, i, numShards)));
    }

    List<String> actualElements = new ArrayList<>();
    for (File outputFile : expectedFiles) {
      assertTrue("Expected output file " + outputFile.getName(), outputFile.exists());
      try (DataFileReader<String> reader =
          new DataFileReader<>(outputFile, AvroCoder.of(String.class).createDatumReader())) {
        Iterators.addAll(actualElements, reader);
      }
    }
    assertThat(actualElements, containsInAnyOrder(expectedElements));
  }

  @Test
  public void testAvroSinkWrite() throws Exception {
    String[] expectedElements = new String[] {"first", "second", "third"};

    runTestWrite(expectedElements, 1);
  }

  @Test
  public void testAvroSinkShardedWrite() throws Exception {
    String[] expectedElements = new String[] {"first", "second", "third", "fourth", "fifth"};

    runTestWrite(expectedElements, 4);
  }
  // TODO: for Write only, test withSuffix,
  // withShardNameTemplate and withoutSharding.

  @Test
  public void testReadDisplayData() {
    AvroIO.Read.Bound<?> read = AvroIO.Read.from("foo.*")
        .withoutValidation();

    DisplayData displayData = DisplayData.from(read);
    assertThat(displayData, hasDisplayItem("filePattern", "foo.*"));
    assertThat(displayData, hasDisplayItem("validation", false));
  }

  @Test
  public void testWriteDisplayData() {
    AvroIO.Write.Bound<?> write = AvroIO.Write
        .to("foo")
        .withShardNameTemplate("-SS-of-NN-")
        .withSuffix("bar")
        .withSchema(GenericClass.class)
        .withNumShards(100)
        .withoutValidation();

    DisplayData displayData = DisplayData.from(write);

    assertThat(displayData, hasDisplayItem("filePrefix", "foo"));
    assertThat(displayData, hasDisplayItem("shardNameTemplate", "-SS-of-NN-"));
    assertThat(displayData, hasDisplayItem("fileSuffix", "bar"));
    assertThat(displayData, hasDisplayItem("schema", GenericClass.class));
    assertThat(displayData, hasDisplayItem("numShards", 100));
    assertThat(displayData, hasDisplayItem("validation", false));
  }

  @Test
  public void testPrimitiveWriteDisplayData() {
    DisplayDataEvaluator evaluator = DataflowDisplayDataEvaluator.create();

    AvroIO.Write.Bound<?> write = AvroIO.Write
        .to("foo")
        .withSchema(Schema.create(Schema.Type.STRING))
        .withoutValidation();

    Set<DisplayData> displayData = evaluator.displayDataForPrimitiveTransforms(write);
    assertThat("AvroIO.Write should include the file pattern in its primitive transform",
        displayData, hasItem(hasDisplayItem("fileNamePattern")));
  }

  @Test
  public void testPrimitiveReadDisplayData() {
    DisplayDataEvaluator evaluator = DataflowDisplayDataEvaluator.create();

    AvroIO.Read.Bound<?> read = AvroIO.Read.from("foo.*")
        .withSchema(Schema.create(Schema.Type.STRING))
        .withoutValidation();

    Set<DisplayData> displayData = evaluator.displayDataForPrimitiveTransforms(read);
    assertThat("AvroIO.Read should include the file pattern in its primitive transform",
        displayData, hasItem(hasDisplayItem("filePattern")));
  }
}


text: export { FileUploaderModule } from './file-uploader.module';


text:
package com.uiresource.cookit;

import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentTransaction;
import android.text.Spannable;
import android.text.SpannableString;
import android.util.Log;
import android.view.MenuInflater;
import android.view.SubMenu;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.uiresource.cookit.utils.AppBarStateChangeListener;
import com.uiresource.cookit.utils.CircleGlide;
import com.uiresource.cookit.utils.CustomTypefaceSpan;

public class Main extends BaseActivity
        implements NavigationView.OnNavigationItemSelectedListener {
    DrawerLayout drawer;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        setupToolbar(R.id.toolbar, "COOK IT", R.color.colorPink, R.color.colorWhiteTrans, R.drawable.ic_burger);

        FragmentTransaction ft;
        FragmentHome fragmentHome = new FragmentHome();
        ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.frameLayout, fragmentHome).commit();

        drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        Menu m = navigationView.getMenu();
        for (int i=0;i<m.size();i++) {
            MenuItem mi = m.getItem(i);
            SubMenu subMenu = mi.getSubMenu();
            if (subMenu!=null && subMenu.size() >0 ) {
                for (int j=0; j <subMenu.size();j++) {
                    MenuItem subMenuItem = subMenu.getItem(j);
                    applyFontToMenuItem(subMenuItem);
                }
            }
            applyFontToMenuItem(mi);
        }

        View header = navigationView.getHeaderView(0);
        ImageView imageView = (ImageView) header.findViewById(R.id.imageView);
        Glide.with(this)
                .load(Uri.parse("https://s3.amazonaws.com/uifaces/faces/twitter/jsa/128.jpg"))
                .transform(new CircleGlide(this))
                .into(imageView);
    }
    private void applyFontToMenuItem(MenuItem mi) {
        Typeface font = Typeface.createFromAsset(getAssets(), "fonts/SourceSansPro-Semibold.otf");
        SpannableString mNewTitle = new SpannableString(mi.getTitle());
        mNewTitle.setSpan(new CustomTypefaceSpan("" , font), 0 , mNewTitle.length(),  Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        mi.setTitle(mNewTitle);
    }
    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        switch (item.getItemId()) {
            case android.R.id.home:
                drawer.openDrawer(GravityCompat.START);  // OPEN DRAWER
                return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.new_recipe) {
            // Handle the camera action
        } else if (id == R.id.recipes) {

        } else if (id == R.id.saved) {

        } else if (id == R.id.shop_list) {

        } else if (id == R.id.setting) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}


text:
package org.apache.kafka.streams.kstream.internals;

import org.apache.kafka.streams.kstream.ForeachAction;
import org.apache.kafka.streams.kstream.KeyValueMapper;

import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

public class PrintForeachAction<K, V> implements ForeachAction<K, V> {

    private final String label;
    private final PrintWriter printWriter;
    private final boolean closable;
    private final KeyValueMapper<? super K, ? super V, String> mapper;

    /**
     * Print customized output with given writer. The {@link OutputStream} can be {@link System#out} or the others.
     *
     * @param outputStream The output stream to write to.
     * @param mapper The mapper which can allow user to customize output will be printed.
     * @param label The given name will be printed.
     */
    PrintForeachAction(final OutputStream outputStream,
                       final KeyValueMapper<? super K, ? super V, String> mapper,
                       final String label) {
        this.printWriter = new PrintWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
        this.closable = outputStream != System.out && outputStream != System.err;
        this.mapper = mapper;
        this.label = label;
    }

    @Override
    public void apply(final K key, final V value) {
        final String data = String.format("[%s]: %s", label, mapper.apply(key, value));
        printWriter.println(data);
        if (!closable) {
            printWriter.flush();
        }
    }

    public void close() {
        if (closable) {
            printWriter.close();
        } else {
            printWriter.flush();
        }
    }

}


text:
package org.auraframework.service;

import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Nonnull;

import org.auraframework.def.BaseComponentDef;
import org.auraframework.def.ClientLibraryDef;
import org.auraframework.def.DefDescriptor;
import org.auraframework.def.DefDescriptor.DefType;
import org.auraframework.def.Definition;
import org.auraframework.def.DescriptorFilter;
import org.auraframework.def.InterfaceDef;
import org.auraframework.expression.PropertyReference;
import org.auraframework.system.RegistrySet;
import org.auraframework.system.Source;
import org.auraframework.throwable.ClientOutOfSyncException;
import org.auraframework.throwable.quickfix.DefinitionNotFoundException;
import org.auraframework.throwable.quickfix.QuickFixException;

/**
 *

 * Service for loading, finding or interacting with a {@link Definition}.
 *

 *
 * This service should be injected.
 */
public interface DefinitionService extends AuraService {

    /**
     *

     * Create a {@link DefDescriptor} that describes a named {@link Definition}
     *

     *

     * The class must be retrieved from DefDescriptor.DefType.getPrimaryInterface()
     *

     *
     * @param qualifiedName the name of the Definition
     * @param defClass The Interface of the type of definition you are trying to
     *            describe.
     * @return a descriptor. Never returns null.
     */
    <T extends Definition> DefDescriptor<T> getDefDescriptor(String qualifiedName, Class<T> defClass);

    /**
     *

     * Create a {@link DefDescriptor} that describes a named {@link Definition}
     *

     *

     * The class must be retrieved from DefDescriptor.DefType.getPrimaryInterface()
     *

     *
     * @param qualifiedName the name of the Definition
     * @param defClass The Interface of the type of definition you are trying to
     *            describe.
     * @param bundle the bundle for which the descriptor is valid
     * @return a descriptor. Never returns null.
     */
    <T extends Definition, B extends Definition> DefDescriptor<T> getDefDescriptor(String qualifiedName, Class<T> defClass, DefDescriptor bundle);

    /**
     *

     * Create a {@link DefDescriptor} that has the same namespace and name as the provided descriptor but a different
     * DefType and prefix.
     *

     *

     * The class must be retrieved from DefDescriptor.DefType.getPrimaryInterface()
     *

     *
     * @param desc the descriptor of the Definition
     * @param defClass The Interface of the type of definition you are trying to
     *            describe.
     * @return a descriptor. Never returns null.
     */
    <T extends Definition> DefDescriptor<T> getDefDescriptor(DefDescriptor<?> desc, String prefix, Class<T> defClass);

    DefDescriptor<?> getDefDescriptor(String prefix, String namespace, String name, DefType defType);

    /**
     * Add a dynamically generated def to the set of available definitions.
     *
     * @param def The definition to add.
     */
    <D extends Definition> void addDynamicDef(D def);

    /**
     * Get the Definition associated with the descriptor passed in, compiling if
     * necessary.
     *
     * @param descriptor the descriptor to get/compile
     * @return The named definition
     * @throws DefinitionNotFoundException if definition does not exist
     * @throws QuickFixException
     */
    <T extends Definition> T getDefinition(DefDescriptor<T> descriptor) throws DefinitionNotFoundException,
    QuickFixException;

    /**
     * Creates a {@link DefDescriptor} from the qualified name passed in,
     * retrieves the named Definition and then returns it.
     *
     * FIXME: some callers use a descriptorName instead of a qualifiedName here!
     *
     * @return The named definition
     * @throws DefinitionNotFoundException if definition does not exist
     * @throws QuickFixException
     */
    <T extends Definition> T getDefinition(String qualifiedName, Class<T> defType) throws DefinitionNotFoundException,
    QuickFixException;

    /**
     * Return the definition for this descriptor, or null if it does not exist.
     *
     * If the definition was not already compiled, this method will cause it to
     * be compiled before it is returned. The difference with getDefinition is that it will not
     * load all of the dependent defs, and thus will _not_ load the def into the request local cache.
     *
     * Use with care.
     *
     * @param descriptor the descriptor to find.
     * @return the corresponding definition, or null if it doesn't exist.
     * @throws QuickFixException if there is a compile time error.
     */
    <D extends Definition> D getUnlinkedDefinition(DefDescriptor<D> descriptor) throws QuickFixException;

    /**
     * Returns true if the source related to the descriptor exists. Does not
     * compile the definition if it was not already compiled, and does not
     * guarantee that it can compile.
     */
    <D extends Definition> boolean exists(DefDescriptor<D> descriptor);

    /**
     * Get the source for a given descriptor.
     */
    <D extends Definition> Source<D> getSource(DefDescriptor<D> descriptor);

    /**
     * Given a string that contains search patterns or wildcards, return a set
     * of Descriptors for all existing Definitions who have source that exists.
     * Does not compile the definitions if they were not already compiled, and
     * does not guarantee that they can compile.
     *
     * @param matcher the matcher to find descriptors
     * @param referenceDescriptor if matcher contains a wildcard, will be used to filter matches based on access
     */
    Set<DefDescriptor<?>> find(DescriptorFilter matcher, BaseComponentDef referenceDescriptor);

    /**
     * Find the set of components that have a tag.
     *
     * For a component to be returned here, it must implement the PlatformDef interface
     * and have one of the tags passed in.
     *
     * @param tags the set of requested tags (any tag suffices)
     * @return the set of descriptors for defs that match.
     * @deprecated use #findByTags(null, tags)
     */
    @Nonnull
    @Deprecated
    default Set<DefDescriptor<?>> findByTags(@Nonnull Set<String> tags) { return findByTags(null, tags);};

    /**
     * Find the set of components that have a tag.
     *
     * For a component to be returned here, it must implement the PlatformDef interface
     * and have one of the tags passed in.
     *
     * @param namespace a set of namespaces by which to filter the search, null means do not filter.
     * @param tags the set of requested tags (any tag suffices)
     * @return the set of descriptors for defs that match.
     */
    @Nonnull
    Set<DefDescriptor<?>> findByTags(Set<String> namespaces, @Nonnull Set<String> tags);

    /**
     * Given a string that contains search patterns or wildcards, return a set
     * of Descriptors for all existing Definitions who have source that exists.
     * Does not compile the definitions if they were not already compiled, and
     * does not guarantee that they can compile.
     *
     * @param matcher the matcher to find descriptors
     */
    default Set<DefDescriptor<?>> find(DescriptorFilter matcher) {
        return this.find(matcher, null);
    }

    /**
     * update the set of loaded descriptors, and validate.
     *
     * @param loading the descriptor that we are loading if any.
     * @throws ClientOutOfSyncException if one of the defs is out of date.
     * @throws QuickFixException if a definition can't be compiled.
     */
    void updateLoaded(DefDescriptor<?> loading) throws QuickFixException, ClientOutOfSyncException;

    /**
     * Get the UID associated with a descriptor.
     *
     * This call must be made before any of the other UID based functions.
     * Failing to do so will give incorrect results (null).
     *
     * @param uid the old uid (or null if none).
     * @param descriptor the top level descriptor for which we need the UID.
     * @return Either the uid passed in, or if that was null, the correct UID
     * @throws ClientOutOfSyncException if the UID is not null, and was a mismatch
     * @throws QuickFixException if the definition cannot be compiled.
     */
    <T extends Definition> String getUid(String uid, DefDescriptor<T> descriptor) throws ClientOutOfSyncException,
            QuickFixException;

    /**
     * Get the dependencies for a descriptor.
     *
     * This set is guaranteed to be in order of 'use' in that a component should come before
     * all components that use it or depend on it.
     *
     * @param uid the UID for the definition (must have called {@link #getUid(String, DefDescriptor<?>)}).
     */
    Set<DefDescriptor<?>> getDependencies(String uid);

    /**
     * Returns list of client libraries for given uid
     *
     * @param uid uid of app or cmp
     * @return list of client libraries for uid
     */
    List<ClientLibraryDef> getClientLibraries(String uid);

    /**
     * Get a usage map for a global value provider based on the uid.
     *
     * @param uid the UID for the definition (must have called {@link #getUid(String, DefDescriptor<?>)}).
     * @param root the root for the global value provider.
     * @return a usage map.
     */
    Set<PropertyReference> getGlobalReferences(String uid, String root);

    /**
     * Check to see if the dependency set is cacheable or not.
     *
     * This is really about wether we expect the definition to change. If not, we can cache based on
     * descriptor rather than uid, and we can expect those to be 'permanent'. If the entry is not
     * cacheable, the UID should still give us the ability to cache, but we must be carefull about permanence,
     * as the defintion may be dynamic.
     */
    boolean isDependencySetCacheable(String uid);

    /**
     * assert that the referencingDescriptor has access to the definition.
     *
     * @param referencingDescriptor the descriptor of the component referencing the definition.
     * @param def the definition being referenced.
     * @throws QuickFixException if the reference is not allowed
     */
    <D extends Definition> void assertAccess(DefDescriptor<?> referencingDescriptor, D def) throws QuickFixException;

    /**
     * assert that the referencingDescriptor has access to the definition.
     *
     * @param referencingDescriptor the descriptor of the component referencing the definition.
     * @param accessDescriptor a descriptor for a definition being accessed.
     * @throws QuickFixException if the reference is not allowed
     */
    <D extends Definition> void assertAccess(DefDescriptor<?> referencingDescriptor, DefDescriptor<?> accessDescriptor) throws QuickFixException;

    /**
     * Populate a global value provider from references in a set of definitions.
     *
     * This routine will populate the global value provider, and capture any errors during the process. If
     * errors occur, it will throw an exception which will be a composite exception of all errors.
     *
     * @param root the root name of the GVP.
     * @param definitionMap A map of descriptor to definition that defines the set of definitions to use.
     * @throws QuickFixException if any errors occurred, the exception will be thrown after the entire set is processed
     */
    void populateGlobalValues(String root, Map<DefDescriptor<? extends Definition>, Definition> definitionMap)
        throws QuickFixException;

    /**
     * Retrieve a set of references to a global value provider, validating them.
     *
     * This routine will fetch the set of global value provider references for a given root, validating each one,
     * and throwing a composite error if validation fails.
     *
     * @param root the root name of the GVP.
     * @param definitionMap A map of descriptor to definition that defines the set of definitions to use.
     * @throws QuickFixException if any errors occurred, the exception will be thrown after the entire set is processed
     */
    Set<String> getGlobalReferences(String root, Map<DefDescriptor<? extends Definition>, Definition> definitionMap)
        throws QuickFixException;

    /**
     * Returns null if the referencingDescriptor has access to the definition otherwise a specific access violation reason.
     */
    boolean hasAccess(DefDescriptor<?> referencingDescriptor, DefDescriptor<?> accessDescriptor) throws QuickFixException;

    <D extends Definition> boolean hasAccess(DefDescriptor<?> referencingDescriptor, D def) throws QuickFixException;

    /**
     * @param descriptor
     * @param interfaceDef
     * @return true if the definition or it's parent (extends) definitions contain the interface
     * @throws QuickFixException
     */
    boolean hasInterface(DefDescriptor<? extends BaseComponentDef> descriptor, DefDescriptor<InterfaceDef> interfaceDef) throws QuickFixException;

    /**
     * make sure all of our registries are built.
     */
    void warmCaches();

    public interface ResolverContext {
        RegistrySet getRegistrySet();
    }

    /**
     * create a "context" for resolving definitions.
     *
     * This method, along with #setResolverContext(Object) can be used to manage the set of
     * definitions available to the definition Service. During normal run-time, these methods
     * should not be needed.
     *
     * The use case for this set of methods is when you want to update a set of definitions, and
     * you need to validate the new definitions together as a set, and check them against the
     * previous set of definitions. In the case of using some sort of database to save the defs,
     * this will allow both the old and new definitions to be held simultaniously, and allow
     * the caller to control which set is currently in use.
     *
     * @param registrySet the registry set for which we need a context.
     * @return the context.
     */
    ResolverContext createResolverContext(RegistrySet registrySet);

    /**
     * set the current registry set context.
     *
     * @param context A context created by #createRegistrySetContext().
     */
    void setResolverContext(ResolverContext context);
}


text:
layout: post
title: "Run #2"
tags:
  - run
  - trail
---

* 4 Miles
* 1000+ vertical feet
* Rattlesnake Ledge

Roughly 1.5 hours up and back.  Failed to set Nike+ correctly...


text:
<!doctype html>

    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <title>Retrospective - KW8</title>
    <link rel="stylesheet" type="text/css" media="screen, projection, print"
     href="slidy.css" />
    <link rel="stylesheet" type="text/css" media="screen, projection, print"
     href="style.css" />

<link rel="stylesheet" href="styles/monokai.css">


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Peronospora hornungiae A. Gustavsson

### Remarks
null


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">

<link rel="stylesheet" href="../skin/tigris.css" type="text/css">
<link rel="stylesheet" href="../skin/mysite.css" type="text/css">
<link rel="stylesheet" href="../skin/site.css" type="text/css">
<link media="print" rel="stylesheet" href="../skin/print.css" type="text/css">
<title>Hacking HSSF</title>

Apache | POI

Home |

Apache POI

Top

HSSF+XSSF

Overview

Quick Guide

HOWTO

HSSF to SS Converting

Formula Support

Formula Evaluation

Eval Dev Guide

Examples

Use Case

Pictorial Docs

Limitations

User Defined Functions

ExcelAnt Tests

Contributer's Guide

Hacking HSSF

Record Generator

Charts

<form target="_blank" action="https://www.google.com/search" method="get">

                          Search Apache POI

<input value="poi.apache.org" name="sitesearch" type="hidden"><input size="10" name="q" id="query" type="text"><input name="Search" value="GO" type="submit">

</form>

Hacking HSSF

Where Can I Find Documentation on Feature X#

                You might find the
                'Excel 97 Developer's Kit' (out of print, Microsoft Press, no
                restrictive covenants, available on Amazon.com) helpful for
                understanding the file format.

                Also useful is the open office XLS spec.  We
                are collaborating with the maintainer of the spec so if you think you can add something to their
                document just send through your changes.

Help, I Can't Find Feature X Documented Anywhere#

                Look at OpenOffice.org or Gnumeric sources if its implemented there.

                Use org.apache.poi.hssf.dev.BiffViewer to view the structure of the
                file.  Experiment by adding one criteria entry at a time.  See what it
                does to the structure, infer behavior and structure from it.  Using the
                unix diff command (or get cygwin from www.cygwin.com for windows) you
                can figure out a lot very quickly. Unimplemented records show up as
                'UNKNOWN' and prints a hex dump.

Low-level Record Generation#

                Low level records can be time consuming to created.  We created a record
                generator to help generate some of the simpler tasks.

                We use XML
                descriptors to generate the Java code (which sure beats the heck out of
                the PERL scripts originally used ;-) for low level records.  The
                generator is kinda alpha-ish right now and could use some enhancement,
                so you may find that to be about 1/2 of the work.  Notice this is in
                org.apache.poi.hssf.record.definitions.

Important Notice#

One thing to note:  If you are making a large code contribution we need to ensure
            any participants in this process have never
            signed a "Non Disclosure Agreement" with Microsoft, and have not
            received any information covered by such an agreement.  If they have
            they'll not be able to participate in the POI project.  For large contributions we
            may ask you to sign an agreement.

What Can I Work On?#

Check our todo list or simply look for missing functionality.  Start small
            and work your way up.

What Else Should I Know?#

Make sure you read the contributing section
            as it contains more generation information about contributing to POI in general.

by Glen Stampoultzis, Andrew Oliver

              Copyright © 2002-2016 The Apache Software Foundation. All rights reserved.

              Apache, Apache POI, and the Apache POI logo are registered trademarks or
              trademarks of The Apache Software Foundation in the U.S. and/or other countries.


text:
package org.javamoney.cdi;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import static org.junit.Assert.assertNotNull;

/**
 * Tests format related injection.
 */
public class FormatInjectionTest {

    private static FormatInjectedBean bean;

    @BeforeClass
    public static final void startContainer() {
        SEContainer.start();
        bean = SEContainer.getInstance(FormatInjectedBean.class);
    }

    @Test
    public void defaultFormat(){
        assertNotNull(bean.defaultFormat);
    }

    @Test
    public void defaultFormats(){
        assertNotNull(bean.defaultFormats);
    }

    @Test
    public void defaultWithCustomSeparator(){
        assertNotNull(bean.defaultWithCustomSeparator);
    }

    @Test
    public void germanFormats(){
        assertNotNull(bean.germanFormats);
    }

    @Test
    public void isoProviderFormat(){
        assertNotNull(bean.isoProviderFormat);
    }

    @AfterClass
    public static final void stopContainer() {
        SEContainer.stop();
    }
}


text:
import java.net.Socket;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class GlobalSocketStore {

	public static Map<String, Socket> sGlobalSocketMap = new ConcurrentHashMap<String, Socket>();

	public static void put(String id, Socket socket) {
		sGlobalSocketMap.put(id, socket);
	}

	public static Socket get(String id) {
		return sGlobalSocketMap.get(id);
	}

	public static void remove(String key) {
		sGlobalSocketMap.remove(key);
	}

}


text:
using namespace greentop;

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

    if (argc < 5) {
        std::cerr << "Usage: " << argv[0] << " <application key> <username> <password> <event type id>" << std::endl;
        return 1;
    }

    ExchangeApi::Exchange exchange = ExchangeApi::Exchange::AUS;

    ExchangeApi exchangeApi(argv[1]);

    if (exchangeApi.login(argv[2], argv[3])) {

        MarketFilter filter;
        std::set<std::string> eventTypeIds = {argv[4]};
        filter.setEventTypeIds(eventTypeIds);
        ListCompetitionsRequest req(filter);

        if (req.isValid()) {

            ListCompetitionsResponse resp = exchangeApi.listCompetitions(exchange, req);

            if (resp.isSuccess()) {

                std::vector<CompetitionResult> competitionResults = resp.getCompetitionResults();

                for (unsigned i = 0; i < competitionResults.size(); ++i) {
                    Competition competition = competitionResults[i].getCompetition();
                    std::cout << competition.getId() << " " << competition.getName() << std::endl;
                }

            } else {
                std::cout << "request failed: " << resp.getFaultCode() << " " << resp.getFaultString() << std::endl;
            }
        } else {
            std::cout << "invalid request: " << req.toString() << std::endl;
        }

    } else {
        std::cout << "failed to log in" << std::endl;
    }

}


text:
require 'securerandom'

class OpenConferenceWare::InstallGenerator < Rails::Generators::Base
  source_root File.expand_path('../templates', __FILE__)

  argument :mount_point,
    type: :string,
    default: "/",
    desc: "The path where OpenConferenceWare should be mounted",
    banner: "MOUNT_POINT (Default: /)"

  def copy_config_initializer
    template "config_initializer.rb", "config/initializers/01_open_conference_ware.rb"
  end

  def copy_omniauth_initializer
    copy_file "omniauth_initializer.rb", "config/initializers/02_omniauth.rb"
  end

  def generate_secrets_yml
    template "secrets.yml.erb", "config/secrets.yml"
  end

  def mount_engine
    route %Q{mount OpenConferenceWare::Engine => "#{mount_point}"}
  end

  def replace_secret_token_initializer
    template "secret_token.rb.erb", "config/initializers/secret_token.rb"
  end

  def include_engine_seeds
    append_to_file "db/seeds.rb" do
      <<-SEED

# Include OpenConferenceWare's seed data
OpenConferenceWare::Engine.load_seed
      SEED
    end
  end

  def run_setup_rake_task
    rake "open_conference_ware:setup"
  end
end


text:
using System;
using TechTalk.SpecFlow;

namespace Specification.Examples
{
    using NUnit.Framework;

    [Binding]
    public class ImperativeSteps
    {
        [Given(@"I am on the application start screen")]
        public void GivenIAmOnTheApplicationStartScreen()
        {
            Assert.AreEqual(3,3);
        }

        [Given(@"I enter a first name of Sherlock")]
        public void GivenIEnterAFirstNameOfSherlock()
        {
            Assert.IsTrue(true);
        }

        [Given(@"I enter a last name of Holmes")]
        public void GivenIEnterALastNameOfHolmes()
        {
            Assert.IsFalse(false);
        }

        [When(@"I submit my form")]
        public void WhenISubmitMyForm()
        {

        }

        [Then(@"I should see the application complete confirmation for Sherlock")]
        public void ThenIShouldSeeTheApplicationCompleteConfirmationForSherlock()
        {
           Assert.AreNotEqual(3,4);
        }
    }
}


text:
using namespace std;

//////////////////////////////////////////////////////////////////////////////
//
// BitcoinMiner
//

string strMintMessage = "Info: Minting suspended due to locked wallet.";
string strMintWarning;
extern unsigned int nMinerSleep;

int static FormatHashBlocks(void* pbuffer, unsigned int len)
{
    unsigned char* pdata = (unsigned char*)pbuffer;
    unsigned int blocks = 1 + ((len + 8) / 64);
    unsigned char* pend = pdata + 64 * blocks;
    memset(pdata + len, 0, 64 * blocks - len);
    pdata[len] = 0x80;
    unsigned int bits = len * 8;
    pend[-1] = (bits >> 0) & 0xff;
    pend[-2] = (bits >> 8) & 0xff;
    pend[-3] = (bits >> 16) & 0xff;
    pend[-4] = (bits >> 24) & 0xff;
    return blocks;
}

static const unsigned int pSHA256InitState[8] =
{0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};

void SHA256Transform(void* pstate, void* pinput, const void* pinit)
{
    SHA256_CTX ctx;
    unsigned char data[64];

    SHA256_Init(&ctx);

    for (int i = 0; i < 16; i++)
        ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);

    for (int i = 0; i < 8; i++)
        ctx.h[i] = ((uint32_t*)pinit)[i];

    SHA256_Update(&ctx, data, sizeof(data));
    for (int i = 0; i < 8; i++)
        ((uint32_t*)pstate)[i] = ctx.h[i];
}

// Some explaining would be appreciated
class COrphan
{
public:
    CTransaction* ptx;
    set<uint256> setDependsOn;
    double dPriority;
    double dFeePerKb;

    COrphan(CTransaction* ptxIn)
    {
        ptx = ptxIn;
        dPriority = dFeePerKb = 0;
    }

    void print() const
    {
        printf("COrphan(hash=%s, dPriority=%.1f, dFeePerKb=%.1f)\n",
               ptx->GetHash().ToString().substr(0,10).c_str(), dPriority, dFeePerKb);
        BOOST_FOREACH(uint256 hash, setDependsOn)
            printf("   setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
    }
};

uint64 nLastBlockTx = 0;
uint64 nLastBlockSize = 0;
int64 nLastCoinStakeSearchInterval = 0;

// We want to sort transactions by priority and fee, so:
typedef boost::tuple<double, double, CTransaction*> TxPriority;
class TxPriorityCompare
{
    bool byFee;
public:
    TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
    bool operator()(const TxPriority& a, const TxPriority& b)
    {
        if (byFee)
        {
            if (a.get<1>() == b.get<1>())
                return a.get<0>() < b.get<0>();
            return a.get<1>() < b.get<1>();
        }
        else
        {
            if (a.get<0>() == b.get<0>())
                return a.get<1>() < b.get<1>();
            return a.get<0>() < b.get<0>();
        }
    }
};

// CreateNewBlock:
//   fProofOfStake: try (best effort) to make a proof-of-stake block
CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake)
{
    // Create new block
    auto_ptr<CBlock> pblock(new CBlock());
    if (!pblock.get())
        return NULL;

    // Create coinbase tx
    CTransaction txNew;
    txNew.vin.resize(1);
    txNew.vin[0].prevout.SetNull();
    txNew.vout.resize(1);

    if (!fProofOfStake)
    {
        CBitcoinAddress address(!fTestNet ? FOUNDATION_ADDRESS : FOUNDATION_ADDRESS_TEST);
        txNew.vout.resize(2);
        CReserveKey reservekey(pwallet);
        txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
        txNew.vout[1].scriptPubKey.SetDestination(address.Get());

    }
    else
        txNew.vout[0].SetEmpty();

    // Add our coinbase tx as first transaction
    pblock->vtx.push_back(txNew);

    // Largest block you're willing to create:
    unsigned int nBlockMaxSize = GetArg("-blockmaxsize", MAX_BLOCK_SIZE_GEN/2);
    // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
    nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));

    // How much of the block should be dedicated to high-priority transactions,
    // included regardless of the fees they pay
    unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", 27000);
    nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);

    // Minimum block size you want to create; block will be filled with free transactions
    // until there are no more or the block reaches this size:
    unsigned int nBlockMinSize = GetArg("-blockminsize", 0);
    nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);

    // Fee-per-kilobyte amount considered the same as "free"
    // Be careful setting this: if you set it to zero then
    // a transaction spammer can cheaply fill blocks using
    // 1-satoshi-fee transactions. It should be set above the real
    // cost to you of processing a transaction.
    int64 nMinTxFee = MIN_TX_FEE;
    if (mapArgs.count("-mintxfee"))
        ParseMoney(mapArgs["-mintxfee"], nMinTxFee);

    CBlockIndex* pindexPrev = pindexBest;

    pblock->nBits = GetNextTargetRequired(pindexPrev, fProofOfStake);

    // Collect memory pool transactions into the block
    int64 nFees = 0;
    {
        LOCK2(cs_main, mempool.cs);
        CBlockIndex* pindexPrev = pindexBest;
        CTxDB txdb("r");

        // Priority order to process transactions
        list<COrphan> vOrphan; // list memory doesn't move
        map<uint256, vector<COrphan*> > mapDependers;

        // This vector will be sorted into a priority queue:
        vector<TxPriority> vecPriority;
        vecPriority.reserve(mempool.mapTx.size());
        for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
        {
            CTransaction& tx = (*mi).second;
            if (tx.IsCoinBase() || tx.IsCoinStake() || !tx.IsFinal())
                continue;

            COrphan* porphan = NULL;
            double dPriority = 0;
            int64 nTotalIn = 0;
            bool fMissingInputs = false;
            BOOST_FOREACH(const CTxIn& txin, tx.vin)
            {
                // Read prev transaction
                CTransaction txPrev;
                CTxIndex txindex;
                if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
                {
                    // This should never happen; all transactions in the memory
                    // pool should connect to either transactions in the chain
                    // or other transactions in the memory pool.
                    if (!mempool.mapTx.count(txin.prevout.hash))
                    {
                        printf("ERROR: mempool transaction missing input\n");
                        if (fDebug) assert("mempool transaction missing input" == 0);
                        fMissingInputs = true;
                        if (porphan)
                            vOrphan.pop_back();
                        break;
                    }

                    // Has to wait for dependencies
                    if (!porphan)
                    {
                        // Use list for automatic deletion
                        vOrphan.push_back(COrphan(&tx));
                        porphan = &vOrphan.back();
                    }
                    mapDependers[txin.prevout.hash].push_back(porphan);
                    porphan->setDependsOn.insert(txin.prevout.hash);
                    nTotalIn += mempool.mapTx[txin.prevout.hash].vout[txin.prevout.n].nValue;
                    continue;
                }
                int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
                nTotalIn += nValueIn;

                int nConf = txindex.GetDepthInMainChain();
                dPriority += (double)nValueIn * nConf;
            }
            if (fMissingInputs) continue;

            // Priority is sum(valuein * age) / txsize
            unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
            dPriority /= nTxSize;

            // This is a more accurate fee-per-kilobyte than is used by the client code, because the
            // client code rounds up the size to the nearest 1K. That's good, because it gives an
            // incentive to create smaller transactions.
            double dFeePerKb =  double(nTotalIn-tx.GetValueOut()) / (double(nTxSize)/1000.0);

            if (porphan)
            {
                porphan->dPriority = dPriority;
                porphan->dFeePerKb = dFeePerKb;
            }
            else
                vecPriority.push_back(TxPriority(dPriority, dFeePerKb, &(*mi).second));
        }

        // Collect transactions into block
        map<uint256, CTxIndex> mapTestPool;
        uint64 nBlockSize = 1000;
        uint64 nBlockTx = 0;
        int nBlockSigOps = 100;
        bool fSortedByFee = (nBlockPrioritySize <= 0);

        TxPriorityCompare comparer(fSortedByFee);
        std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);

        while (!vecPriority.empty())
        {
            // Take highest priority transaction off the priority queue:
            double dPriority = vecPriority.front().get<0>();
            double dFeePerKb = vecPriority.front().get<1>();
            CTransaction& tx = *(vecPriority.front().get<2>());

            std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
            vecPriority.pop_back();

            // Size limits
            unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
            if (nBlockSize + nTxSize >= nBlockMaxSize)
                continue;

            // Legacy limits on sigOps:
            unsigned int nTxSigOps = tx.GetLegacySigOpCount();
            if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
                continue;

            // Timestamp limit
            if (tx.nTime > GetAdjustedTime() || (fProofOfStake && tx.nTime > pblock->vtx[0].nTime))
                continue;

            // Simplify transaction fee - allow free = false
            int64 nMinFee = tx.GetMinFee(nBlockSize, false, GMF_BLOCK);

            // Skip free transactions if we're past the minimum block size:
            if (fSortedByFee && (dFeePerKb < nMinTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
                continue;

            // Prioritize by fee once past the priority size or we run out of high-priority
            // transactions:
            if (!fSortedByFee &&
                ((nBlockSize + nTxSize >= nBlockPrioritySize) || (dPriority < COIN * 144 / 250)))
            {
                fSortedByFee = true;
                comparer = TxPriorityCompare(fSortedByFee);
                std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
            }

            // Connecting shouldn't fail due to dependency on other memory pool transactions
            // because we're already processing them in order of dependency
            map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
            MapPrevTx mapInputs;
            bool fInvalid;
            if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid))
                continue;

            int64 nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
            if (nTxFees < nMinFee)
                continue;

            nTxSigOps += tx.GetP2SHSigOpCount(mapInputs);
            if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
                continue;

            if (!tx.ConnectInputs(txdb, mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true))
                continue;
            mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size());
            swap(mapTestPool, mapTestPoolTmp);

            // Added
            pblock->vtx.push_back(tx);
            nBlockSize += nTxSize;
            ++nBlockTx;
            nBlockSigOps += nTxSigOps;
            nFees += nTxFees;

            if (fDebug && GetBoolArg("-printpriority"))
            {
                printf("priority %.1f feeperkb %.1f txid %s\n",
                       dPriority, dFeePerKb, tx.GetHash().ToString().c_str());
            }

            // Add transactions that depend on this one to the priority queue
            uint256 hash = tx.GetHash();
            if (mapDependers.count(hash))
            {
                BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
                {
                    if (!porphan->setDependsOn.empty())
                    {
                        porphan->setDependsOn.erase(hash);
                        if (porphan->setDependsOn.empty())
                        {
                            vecPriority.push_back(TxPriority(porphan->dPriority, porphan->dFeePerKb, porphan->ptx));
                            std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
                        }
                    }
                }
            }
        }

        nLastBlockTx = nBlockTx;
        nLastBlockSize = nBlockSize;

        if (fDebug && GetBoolArg("-printpriority"))
            printf("CreateNewBlock(): total size %"PRI64u"\n", nBlockSize);

        if (!fProofOfStake)
        {
        	pblock->vtx[0].vout[0].nValue = GetProofOfWorkReward(pblock->nBits);
        	pblock->vtx[0].vout[1].nValue = GetFoundationAmount(pblock->nBits);
        }
        // Fill in header
        pblock->hashPrevBlock = pindexPrev->GetBlockHash();
        pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime());
        pblock->nTime = max(pblock->GetBlockTime(), PastDrift(pindexPrev->GetBlockTime()));
        if (!fProofOfStake)
            pblock->UpdateTime(pindexPrev);
        pblock->nNonce = 0;
    }

    return pblock.release();
}

void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
{
    // Update nExtraNonce
    static uint256 hashPrevBlock;
    if (hashPrevBlock != pblock->hashPrevBlock)
    {
        nExtraNonce = 0;
        hashPrevBlock = pblock->hashPrevBlock;
    }
    ++nExtraNonce;
    unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
    pblock->vtx[0].vin[0].scriptSig = (CScript() << nHeight << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
    assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);

    pblock->hashMerkleRoot = pblock->BuildMerkleTree();
}

void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
{
    //
    // Pre-build hash buffers
    //
    struct
    {
        struct unnamed2
        {
            int nVersion;
            uint256 hashPrevBlock;
            uint256 hashMerkleRoot;
            unsigned int nTime;
            unsigned int nBits;
            unsigned int nNonce;
        }
        block;
        unsigned char pchPadding0[64];
        uint256 hash1;
        unsigned char pchPadding1[64];
    }
    tmp;
    memset(&tmp, 0, sizeof(tmp));

    tmp.block.nVersion       = pblock->nVersion;
    tmp.block.hashPrevBlock  = pblock->hashPrevBlock;
    tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
    tmp.block.nTime          = pblock->nTime;
    tmp.block.nBits          = pblock->nBits;
    tmp.block.nNonce         = pblock->nNonce;

    FormatHashBlocks(&tmp.block, sizeof(tmp.block));
    FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));

    // Byte swap all the input buffer
    for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
        ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);

    // Precalc the first half of the first hash, which stays constant
    SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);

    memcpy(pdata, &tmp.block, 128);
    memcpy(phash1, &tmp.hash1, 64);
}

bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
{
    uint256 hashblock = pblock->GetHash();
    uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();

    if(!pblock->IsProofOfWork())
        return error("CheckWork() : %s is not a proof-of-work block", hashblock.GetHex().c_str());

    if (hashblock > hashTarget)
        return error("CheckWork() : proof-of-work not meeting target");

    //// debug print
    printf("CheckWork() : new proof-of-work block found  \n  hashblock: %s  \ntarget: %s\n", hashblock.GetHex().c_str(), hashTarget.GetHex().c_str());
    pblock->print();
    printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());

    // Found a solution
    {
        LOCK(cs_main);
        if (pblock->hashPrevBlock != hashBestChain)
            return error("CheckWork : generated block is stale");

        // Remove key from key pool
        reservekey.KeepKey();

        // Track how many getdata requests this block gets
        {
            LOCK(wallet.cs_wallet);
            wallet.mapRequestCount[hashblock] = 0;
        }

        // Process this block the same as if we had received it from another node
        if (!ProcessBlock(NULL, pblock))
            return error("CheckWork : ProcessBlock, block not accepted");

        std::string strCmd = GetArg("-powblockfoundnotify", "");
        if (!strCmd.empty())
        {
            boost::replace_all(strCmd, "%s", hashblock.GetHex());
            boost::thread t(runCommand, strCmd); // thread runs free
        }
    }

    return true;
}

bool CheckStake(CBlock* pblock, CWallet& wallet)
{
    uint256 proofHash = 0, hashTarget = 0;
    uint256 hashBlock = pblock->GetHash();

    if(!pblock->IsProofOfStake())
        return error("CheckStake() : %s is not a proof-of-stake block", hashBlock.GetHex().c_str());

    // verify hash target and signature of coinstake tx
    if (!CheckProofOfStake(pblock->vtx[1], pblock->nBits, proofHash, hashTarget))
        return error("CheckStake() : proof-of-stake checking failed");

    //// debug print
    printf("CheckStake() : new proof-of-stake block found \n hash: %s \nproofhash: %s \ntarget: %s\n", hashBlock.GetHex().c_str(), proofHash.GetHex().c_str(), hashTarget.GetHex().c_str());
    pblock->print();
    printf("out %s\n", FormatMoney(pblock->vtx[1].GetValueOut()).c_str());

    // Found a solution
    {
        LOCK(cs_main);
        if (pblock->hashPrevBlock != hashBestChain)
            return error("CheckStake() : generated block is stale");

        // Track how many getdata requests this block gets
        {
            LOCK(wallet.cs_wallet);
            wallet.mapRequestCount[hashBlock] = 0;
        }

        // Process this block the same as if we had received it from another node
        if (!ProcessBlock(NULL, pblock))
            return error("CheckStake() : ProcessBlock, block not accepted");

        std::string strCmd = GetArg("-posblockfoundnotify", "");
        if (!strCmd.empty())
        {
            boost::replace_all(strCmd, "%s", hashBlock.GetHex());
            boost::thread t(runCommand, strCmd); // thread runs free
        }
    }

    return true;
}

void static ThreadBitcoinMiner(void* parg);

static bool fGenerateBitcoins = false;
static bool fLimitProcessors = false;
static int nLimitProcessors = -1;

void BitcoinMiner(CWallet *pwallet)
{
    void *scratchbuf = scrypt_buffer_alloc();

    printf("CPUMiner started for proof-of-work\n");
    SetThreadPriority(THREAD_PRIORITY_LOWEST);

    // Make this thread recognisable as the mining thread
    RenameThread("bitcoin-miner");

    // Each thread has its own key and counter
    CReserveKey reservekey(pwallet);
    unsigned int nExtraNonce = 0;

    while (fGenerateBitcoins)
    {
        if (fShutdown)
            return;
        while (vNodes.empty() || IsInitialBlockDownload())
        {
            Sleep(1000);
            if (fShutdown)
                return;
            if ((!fGenerateBitcoins))
                return;
        }

        while (pwallet->IsLocked())
        {
            Sleep(1000);
        }

        //
        // Create new block
        //
        unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
        CBlockIndex* pindexPrev = pindexBest;

        auto_ptr<CBlock> pblock(CreateNewBlock(pwallet, false));
        if (!pblock.get())
            return;
        IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);

        printf("Running BitcoinMiner with %"PRIszu" transactions in block (%u bytes)\n", pblock->vtx.size(),
               ::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION));

        //
        // Pre-build hash buffers
        //
        char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
        char pdatabuf[128+16];    char* pdata     = alignup<16>(pdatabuf);
        char phash1buf[64+16];    char* phash1    = alignup<16>(phash1buf);

        FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);

        unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
        unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);

        //
        // Search
        //
        int64 nStart = GetTime();
        uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();

        unsigned int max_nonce = 0xffff0000;
        block_header res_header;
        uint256 result;

        while (true)
        {
            unsigned int nHashesDone = 0;
            unsigned int nNonceFound;

            nNonceFound = scanhash_scrypt(
                        (block_header *)&pblock->nVersion,
                        scratchbuf,
                        max_nonce,
                        nHashesDone,
                        UBEGIN(result),
                        &res_header
            );

            // Check if something found
            if (nNonceFound != (unsigned int) -1)
            {
                if (result <= hashTarget)
                {
                    // Found a solution
                    pblock->nNonce = nNonceFound;
                    assert(result == pblock->GetHash());
                    if (!pblock->SignBlock(*pwallet))
                    {
                        break;
                    }
                    strMintWarning = "";

                    SetThreadPriority(THREAD_PRIORITY_NORMAL);
                    CheckWork(pblock.get(), *pwallet, reservekey);
                    SetThreadPriority(THREAD_PRIORITY_LOWEST);
                    break;
                }
            }

            // Meter hashes/sec
            static int64 nHashCounter;
            if (nHPSTimerStart == 0)
            {
                nHPSTimerStart = GetTimeMillis();
                nHashCounter = 0;
            }
            else
                nHashCounter += nHashesDone;
            if (GetTimeMillis() - nHPSTimerStart > 4000)
            {
                static CCriticalSection cs;
                {
                    LOCK(cs);
                    if (GetTimeMillis() - nHPSTimerStart > 4000)
                    {
                        dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
                        nHPSTimerStart = GetTimeMillis();
                        nHashCounter = 0;
                        static int64 nLogTime;
                        if (GetTime() - nLogTime > 30 * 60)
                        {
                            nLogTime = GetTime();
                            printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[THREAD_MINER], dHashesPerSec/1000.0);
                        }
                    }
                }
            }

            // Check for stop or if block needs to be rebuilt
            if (fShutdown)
                return;
            if (!fGenerateBitcoins)
                return;
            if (fLimitProcessors && vnThreadsRunning[THREAD_MINER] > nLimitProcessors)
                return;
            if (vNodes.empty())
                break;
            if (nBlockNonce >= 0xffff0000)
                break;
            if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
                break;
            if (pindexPrev != pindexBest)
                break;

            // Update nTime every few seconds
            pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime());
            pblock->nTime = max(pblock->GetBlockTime(), PastDrift(pindexPrev->GetBlockTime()));
            pblock->UpdateTime(pindexPrev);
            nBlockTime = ByteReverse(pblock->nTime);

            if (pblock->GetBlockTime() >= FutureDrift((int64)pblock->vtx[0].nTime))
                break;  // need to update coinbase timestamp
        }
    }

    scrypt_buffer_free(scratchbuf);
}

void static ThreadBitcoinMiner(void* parg)
{
    CWallet* pwallet = (CWallet*)parg;
    try
    {
        vnThreadsRunning[THREAD_MINER]++;
        BitcoinMiner(pwallet);
        vnThreadsRunning[THREAD_MINER]--;
    }
    catch (std::exception& e) {
        vnThreadsRunning[THREAD_MINER]--;
        PrintException(&e, "ThreadBitcoinMiner()");
    } catch (...) {
        vnThreadsRunning[THREAD_MINER]--;
        PrintException(NULL, "ThreadBitcoinMiner()");
    }
    nHPSTimerStart = 0;
    if (vnThreadsRunning[THREAD_MINER] == 0)
        dHashesPerSec = 0;
    printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINER]);
}

void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
{
    fGenerateBitcoins = fGenerate;
    nLimitProcessors = GetArg("-genproclimit", -1);
    if (nLimitProcessors == 0)
        fGenerateBitcoins = false;
    fLimitProcessors = (nLimitProcessors != -1);

    if (fGenerate)
    {
        int nProcessors = boost::thread::hardware_concurrency();
        printf("%d processors\n", nProcessors);
        if (nProcessors < 1)
            nProcessors = 1;
        if (fLimitProcessors && nProcessors > nLimitProcessors)
            nProcessors = nLimitProcessors;
        int nAddThreads = nProcessors - vnThreadsRunning[THREAD_MINER];
        printf("Starting %d BitcoinMiner threads\n", nAddThreads);
        for (int i = 0; i < nAddThreads; i++)
        {
            if (!NewThread(ThreadBitcoinMiner, pwallet))
                printf("Error: NewThread(ThreadBitcoinMiner) failed\n");
            Sleep(10);
        }
    }
}

void StakeMiner(CWallet *pwallet)
{
    SetThreadPriority(THREAD_PRIORITY_LOWEST);

    // Make this thread recognisable as the mining thread
    RenameThread("stake-miner");

    // Each thread has its own counter
    unsigned int nExtraNonce = 0;

    while (true)
    {
        if (fShutdown)
            return;

        while (pwallet->IsLocked())
        {
            Sleep(1000);
            if (fShutdown)
                return;
        }

        strMintWarning = "";

        while (vNodes.empty() || IsInitialBlockDownload())
        {
            Sleep(1000);
            if (fShutdown)
                return;
        }

        //
        // Create new block
        //
        CBlockIndex* pindexPrev = pindexBest;

        auto_ptr<CBlock> pblock(CreateNewBlock(pwallet, true));
        if (!pblock.get())
            return;
        IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);

        // Trying to sign a block
        if (pblock->SignPoSBlock(*pwallet))
        {
            SetThreadPriority(THREAD_PRIORITY_NORMAL);
            CheckStake(pblock.get(), *pwallet);
            SetThreadPriority(THREAD_PRIORITY_LOWEST);
            Sleep(500);
        }
        Sleep(nMinerSleep);
        continue;
    }
}