text:
package m3

import (
	"bytes"
	"math/rand"
	"net"
	"os"
	"strconv"
	"strings"
	"sync"
	"sync/atomic"
	"testing"
	"time"

	tally "github.com/uber-go/tally/v4"
	customtransport "github.com/uber-go/tally/v4/m3/customtransports"
	m3thrift "github.com/uber-go/tally/v4/m3/thrift/v2"
	"github.com/uber-go/tally/v4/m3/thriftudp"
	"github.com/uber-go/tally/v4/thirdparty/github.com/apache/thrift/lib/go/thrift"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

const (
	queueSize     = 1000
	includeHost   = true
	maxPacketSize = int32(1440)
	shortInterval = 10 * time.Millisecond
)

var (
	localListenAddr   = &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)}
	defaultCommonTags = map[string]string{"env": "test", "host": "test"}
)

var protocols = []Protocol{Compact, Binary}

// TestReporter tests the reporter works as expected with both compact and binary protocols
func TestReporter(t *testing.T) {
	for _, protocol := range protocols {
		var wg sync.WaitGroup
		server := newFakeM3Server(t, &wg, true, protocol)
		go server.Serve()
		defer server.Close()

		commonTags = map[string]string{
			"env":        "development",
			"host":       hostname(),
			"commonTag":  "common",
			"commonTag2": "tag",
			"commonTag3": "val",
		}
		r, err := NewReporter(Options{
			HostPorts:          []string{server.Addr},
			Service:            "test-service",
			CommonTags:         commonTags,
			IncludeHost:        includeHost,
			Protocol:           protocol,
			MaxQueueSize:       queueSize,
			MaxPacketSizeBytes: maxPacketSize,
		})
		require.NoError(t, err)
		defer func() {
			assert.NoError(t, r.Close())
		}()

		tags := map[string]string{"testTag": "TestValue", "testTag2": "TestValue2"}

		wg.Add(2)

		r.AllocateCounter("my-counter", tags).ReportCount(10)
		r.Flush()

		r.AllocateTimer("my-timer", tags).ReportTimer(5 * time.Millisecond)
		r.Flush()

		wg.Wait()

		batches := server.Service.getBatches()
		require.Equal(t, 2, len(batches))

		// Validate common tags
		for _, batch := range batches {
			require.NotNil(t, batch)
			require.True(t, batch.IsSetCommonTags())
			require.Equal(t, len(commonTags)+1, len(batch.GetCommonTags()))
			for _, tag := range batch.GetCommonTags() {
				if tag.GetName() == ServiceTag {
					require.Equal(t, "test-service", tag.GetValue())
				} else {
					require.Equal(t, commonTags[tag.GetName()], tag.GetValue())
				}
			}
		}

		// Validate metrics
		emittedCounters := batches[0].GetMetrics()
		require.Equal(t, 5, len(emittedCounters))
		emittedTimers := batches[1].GetMetrics()
		require.Equal(t, 5, len(emittedTimers))

		emittedCounter, emittedTimer := emittedCounters[0], emittedTimers[0]
		if emittedCounter.GetName() == "my-timer" {
			emittedCounter, emittedTimer = emittedTimer, emittedCounter
		}

		require.Equal(t, "my-counter", emittedCounter.GetName())
		require.True(t, emittedCounter.IsSetTags())
		require.Equal(t, len(tags), len(emittedCounter.GetTags()))
		for _, tag := range emittedCounter.GetTags() {
			require.Equal(t, tags[tag.GetName()], tag.GetValue())
		}
		require.True(t, emittedCounter.IsSetValue())
		emittedVal := emittedCounter.GetValue()
		emittedCount := emittedVal.GetCount()
		require.EqualValues(t, int64(10), emittedCount)

		require.True(t, emittedTimer.IsSetValue())
		emittedVal = emittedTimer.GetValue()
		emittedTimerVal := emittedVal.GetTimer()
		require.EqualValues(t, int64(5*1000*1000), emittedTimerVal)
	}
}

// TestMultiReporter tests the multi Reporter works as expected
func TestMultiReporter(t *testing.T) {
	dests := []string{"127.0.0.1:9052", "127.0.0.1:9053"}
	commonTags := map[string]string{
		"env":        "test",
		"host":       "test",
		"commonTag":  "common",
		"commonTag2": "tag",
		"commonTag3": "val",
	}
	r, err := NewReporter(Options{
		HostPorts:  dests,
		Service:    "test-service",
		CommonTags: commonTags,
	})
	require.NoError(t, err)
	defer r.Close()

	reporter, ok := r.(*reporter)
	require.True(t, ok)
	multitransport, ok := reporter.client.Transport.(*thriftudp.TMultiUDPTransport)
	require.NotNil(t, multitransport)
	require.True(t, ok)
}

// TestNewReporterErrors tests for Reporter creation errors
func TestNewReporterErrors(t *testing.T) {
	var err error
	// Test freeBytes (maxPacketSizeBytes - numOverheadBytes) is negative
	_, err = NewReporter(Options{
		HostPorts:          []string{"127.0.0.1"},
		Service:            "test-service",
		MaxQueueSize:       10,
		MaxPacketSizeBytes: 2 << 5,
	})
	assert.Error(t, err)
	// Test invalid addr
	_, err = NewReporter(Options{
		HostPorts: []string{"fakeAddress"},
		Service:   "test-service",
	})
	assert.Error(t, err)
}

// TestReporterRaceCondition checks if therem is race condition between reporter closing
// and metric reporting, when run with race detector on, this test should pass
func TestReporterRaceCondition(t *testing.T) {
	r, err := NewReporter(Options{
		HostPorts:          []string{"localhost:8888"},
		Service:            "test-service",
		CommonTags:         defaultCommonTags,
		MaxQueueSize:       queueSize,
		MaxPacketSizeBytes: maxPacketSize,
	})
	require.NoError(t, err)

	go func() {
		r.AllocateTimer("my-timer", nil).ReportTimer(10 * time.Millisecond)
	}()
	r.Close()
}

// TestReporterFinalFlush ensures the Reporter emits the last batch of metrics
// after close
func TestReporterFinalFlush(t *testing.T) {
	var wg sync.WaitGroup
	server := newFakeM3Server(t, &wg, true, Compact)
	go server.Serve()
	defer server.Close()

	r, err := NewReporter(Options{
		HostPorts:          []string{server.Addr},
		Service:            "test-service",
		CommonTags:         defaultCommonTags,
		MaxQueueSize:       queueSize,
		MaxPacketSizeBytes: maxPacketSize,
	})
	require.NoError(t, err)

	wg.Add(1)

	r.AllocateTimer("my-timer", nil).ReportTimer(10 * time.Millisecond)
	r.Close()

	wg.Wait()

	require.Equal(t, 1, len(server.Service.getBatches()))
	require.NotNil(t, server.Service.getBatches()[0])
	require.Equal(t, 1, len(server.Service.getBatches()[0].GetMetrics()))
}

// TestReporterNoPanicOnTimerAfterClose ensure the reporter avoids panic
// after close of the reporter when emitting a timer value
func TestReporterNoPanicOnTimerAfterClose(t *testing.T) {
	server := newFakeM3Server(t, &sync.WaitGroup{}, true, Compact)
	go server.Serve()
	defer server.Close()

	r, err := NewReporter(Options{
		HostPorts:          []string{server.Addr},
		Service:            "test-service",
		CommonTags:         defaultCommonTags,
		MaxQueueSize:       queueSize,
		MaxPacketSizeBytes: maxPacketSize,
	})
	require.NoError(t, err)

	timer := r.AllocateTimer("my-timer", nil)
	r.Close()

	assert.NotPanics(t, func() {
		timer.ReportTimer(time.Millisecond)
	})
}

// TestReporterNoPanicOnFlushAfterClose ensure the reporter avoids panic
// after close of the reporter when calling flush
func TestReporterNoPanicOnFlushAfterClose(t *testing.T) {
	server := newFakeM3Server(t, &sync.WaitGroup{}, true, Compact)
	go server.Serve()
	defer server.Close()

	r, err := NewReporter(Options{
		HostPorts:          []string{server.Addr},
		Service:            "test-service",
		CommonTags:         defaultCommonTags,
		MaxQueueSize:       queueSize,
		MaxPacketSizeBytes: maxPacketSize,
	})
	require.NoError(t, err)
	r.Close()

	assert.NotPanics(t, func() {
		r.Flush()
	})
}

func TestReporterHistogram(t *testing.T) {
	var wg sync.WaitGroup
	server := newFakeM3Server(t, &wg, true, Compact)
	go server.Serve()
	defer server.Close()

	r, err := NewReporter(Options{
		HostPorts:          []string{server.Addr},
		Service:            "test-service",
		CommonTags:         defaultCommonTags,
		MaxQueueSize:       queueSize,
		MaxPacketSizeBytes: maxPacketSize,
	})
	require.NoError(t, err)

	wg.Add(1)

	h := r.AllocateHistogram("my-histogram", map[string]string{
		"foo": "bar",
	}, tally.DurationBuckets{
		0 * time.Millisecond,
		25 * time.Millisecond,
		50 * time.Millisecond,
		75 * time.Millisecond,
		100 * time.Millisecond,
	})
	b := h.DurationBucket(0*time.Millisecond, 25*time.Millisecond)
	b.ReportSamples(7)
	b = h.DurationBucket(50*time.Millisecond, 75*time.Millisecond)
	b.ReportSamples(3)
	r.Close()

	wg.Wait()

	require.Equal(t, 1, len(server.Service.getBatches()))
	require.NotNil(t, server.Service.getBatches()[0])
	require.Equal(t, 2, len(server.Service.getBatches()[0].GetMetrics()))

	// Verify first bucket
	counter := server.Service.getBatches()[0].GetMetrics()[0]
	require.Equal(t, "my-histogram", counter.GetName())
	require.True(t, counter.IsSetTags())
	for _, tag := range counter.GetTags() {
		require.Equal(t, map[string]string{
			"foo":      "bar",
			"bucketid": "0001",
			"bucket":   "0-25ms",
		}[tag.GetName()], tag.GetValue())
	}
	require.Equal(t, 3, len(counter.GetTags()))
	require.True(t, counter.IsSetValue())
	val := counter.GetValue()
	count := val.GetCount()
	require.Equal(t, int64(7), count)

	// Verify second bucket
	counter = server.Service.getBatches()[0].GetMetrics()[1]
	require.Equal(t, "my-histogram", counter.GetName())
	require.True(t, counter.IsSetTags())
	require.Equal(t, 3, len(counter.GetTags()))
	for _, tag := range counter.GetTags() {
		require.Equal(t, map[string]string{
			"foo":      "bar",
			"bucketid": "0003",
			"bucket":   "50ms-75ms",
		}[tag.GetName()], tag.GetValue())
	}
	require.True(t, counter.IsSetValue())
	val = counter.GetValue()
	count = val.GetCount()
	require.Equal(t, int64(3), count)
}

func TestBatchSizes(t *testing.T) {
	server := newFakeM3Server(t, nil, false, Compact)
	go server.Serve()
	defer server.Close()

	commonTags := map[string]string{
		"env":    "test",
		"domain": "pod" + strconv.Itoa(rand.Intn(100)),
	}
	maxPacketSize := int32(1440)
	r, err := NewReporter(Options{
		HostPorts:          []string{server.Addr},
		Service:            "test-service",
		CommonTags:         commonTags,
		MaxQueueSize:       10000,
		MaxPacketSizeBytes: maxPacketSize,
	})

	require.NoError(t, err)
	rand.Seed(time.Now().UnixNano())

	var stop uint32
	go func() {
		var (
			counters = make(map[string]tally.CachedCount)
			gauges   = make(map[string]tally.CachedGauge)
			timers   = make(map[string]tally.CachedTimer)
			randTags = func() map[string]string {
				return map[string]string{
					"t1": "val" + strconv.Itoa(rand.Intn(10000)),
				}
			}
		)
		for atomic.LoadUint32(&stop) == 0 {
			metTypeRand := rand.Intn(9)
			name := "size.test.metric.name" + strconv.Itoa(rand.Intn(50))

			if metTypeRand <= 2 {
				_, ok := counters[name]
				if !ok {
					counters[name] = r.AllocateCounter(name, randTags())
				}
				counters[name].ReportCount(rand.Int63n(10000))
			} else if metTypeRand <= 5 {
				_, ok := gauges[name]
				if !ok {
					gauges[name] = r.AllocateGauge(name, randTags())
				}
				gauges[name].ReportGauge(rand.Float64() * 10000)
			} else {
				_, ok := timers[name]
				if !ok {
					timers[name] = r.AllocateTimer(name, randTags())
				}
				timers[name].ReportTimer(time.Duration(rand.Int63n(10000)))
			}
		}
		r.Close()
	}()

	for len(server.Packets()) < 100 {
		time.Sleep(shortInterval)
	}

	atomic.StoreUint32(&stop, 1)
	for _, packet := range server.Packets() {
		require.True(t, len(packet) < int(maxPacketSize))
	}
}

func TestReporterSpecifyService(t *testing.T) {
	commonTags := map[string]string{
		ServiceTag: "overrideService",
		EnvTag:     "test",
		HostTag:    "overrideHost",
	}
	r, err := NewReporter(Options{
		HostPorts:    []string{"127.0.0.1:1000"},
		Service:      "test-service",
		CommonTags:   commonTags,
		IncludeHost:  includeHost,
		MaxQueueSize: 10, MaxPacketSizeBytes: 100,
	})
	require.NoError(t, err)
	defer r.Close()

	reporter, ok := r.(*reporter)
	require.True(t, ok)
	assert.Equal(t, 3, len(reporter.commonTags))
	for _, tag := range reporter.commonTags {
		switch tag.GetName() {
		case ServiceTag:
			assert.Equal(t, "overrideService", tag.GetValue())
		case EnvTag:
			assert.Equal(t, "test", tag.GetValue())
		case HostTag:
			assert.Equal(t, "overrideHost", tag.GetValue())
		}
	}
}

func TestIncludeHost(t *testing.T) {
	var wg sync.WaitGroup
	server := newFakeM3Server(t, &wg, true, Compact)
	go server.Serve()
	defer server.Close()

	commonTags := map[string]string{"env": "test"}
	r, err := NewReporter(Options{
		HostPorts:   []string{server.Addr},
		Service:     "test-service",
		CommonTags:  commonTags,
		IncludeHost: false,
	})
	require.NoError(t, err)
	defer r.Close()
	withoutHost, ok := r.(*reporter)
	require.True(t, ok)
	assert.False(t, tagIncluded(withoutHost.commonTags, "host"))

	r, err = NewReporter(Options{
		HostPorts:   []string{server.Addr},
		Service:     "test-service",
		CommonTags:  commonTags,
		IncludeHost: true,
	})
	require.NoError(t, err)
	defer r.Close()
	withHost, ok := r.(*reporter)
	require.True(t, ok)
	assert.True(t, tagIncluded(withHost.commonTags, "host"))
}

func TestReporterResetTagsAfterReturnToPool(t *testing.T) {
	var wg sync.WaitGroup
	server := newFakeM3Server(t, &wg, false, Compact)
	go server.Serve()
	defer server.Close()

	r, err := NewReporter(Options{
		HostPorts:          []string{server.Addr},
		Service:            "test-service",
		CommonTags:         defaultCommonTags,
		MaxQueueSize:       queueSize,
		MaxPacketSizeBytes: maxPacketSize,
	})
	require.NoError(t, err)
	defer r.Close()

	// Intentionally allocate and leak counters to exhaust metric pool.
	for i := 0; i < metricPoolSize-2; i++ {
		r.AllocateCounter("placeholder", nil)
	}

	// Allocate two counter so there is only one more slot in the pool.
	tags := map[string]string{"tagName1": "tagValue1"}
	c1 := r.AllocateCounter("counterWithTags", tags)

	// Report the counter with tags to take the last slot.
	wg.Add(5)
	c1.ReportCount(1)
	r.Flush()
	wg.Wait()

	// Empty flush to ensure the copied metric is released.
	wg.Add(4)
	r.Flush()
	for {
		rep := r.(*reporter)
		if len(rep.metCh) == 0 {
			break
		}
		time.Sleep(5 * time.Millisecond)
	}

	// Allocate a new counter with no tags reusing the metric
	// just released to the pool.
	c2 := r.AllocateCounter("counterWithNoTags", nil)

	// Report the counter with no tags.
	wg.Add(5)
	c2.ReportCount(1)
	r.Flush()
	wg.Wait()

	// Verify that first reported counter has tags and the second
	// reported counter has no tags.
	metrics := server.Service.getMetrics()
	require.Equal(t, 14, len(metrics)) // 2 test metrics, 4x3 internal metrics

	var filtered []m3thrift.Metric
	for _, metric := range metrics {
		if !strings.HasPrefix(metric.Name, "tally.internal") {
			filtered = append(filtered, metric)
		}
	}
	require.Equal(t, 2, len(filtered))

	require.Equal(t, len(tags), len(filtered[0].GetTags()))
	for _, tag := range filtered[0].GetTags() {
		require.Equal(t, tags[tag.GetName()], tag.GetValue())
	}
	require.Equal(t, 0, len(filtered[1].GetTags()))
}

func TestReporterHasReportingAndTaggingCapability(t *testing.T) {
	r, err := NewReporter(Options{
		HostPorts:  []string{"127.0.0.1:9052"},
		Service:    "test-service",
		CommonTags: defaultCommonTags,
	})
	require.NoError(t, err)

	assert.True(t, r.Capabilities().Reporting())
	assert.True(t, r.Capabilities().Tagging())
}

type fakeM3Server struct {
	t         *testing.T
	Service   *fakeM3Service
	Addr      string
	protocol  Protocol
	processor thrift.TProcessor
	conn      *net.UDPConn
	closed    int32
	packets   fakeM3ServerPackets
}

type fakeM3ServerPackets struct {
	sync.RWMutex
	values [][]byte
}

func newFakeM3Server(t *testing.T, wg *sync.WaitGroup, countBatches bool, protocol Protocol) *fakeM3Server {
	service := newFakeM3Service(wg, countBatches)
	processor := m3thrift.NewM3Processor(service)
	conn, err := net.ListenUDP(localListenAddr.Network(), localListenAddr)
	require.NoError(t, err, "ListenUDP failed")

	return &fakeM3Server{
		t:         t,
		Service:   service,
		Addr:      conn.LocalAddr().String(),
		conn:      conn,
		protocol:  protocol,
		processor: processor,
	}
}

func (f *fakeM3Server) Serve() {
	readBuf := make([]byte, 64000)
	for f.conn != nil {
		n, err := f.conn.Read(readBuf)
		if err != nil {
			if atomic.LoadInt32(&f.closed) == 0 {
				f.t.Errorf("FakeM3Server failed to Read: %v", err)
			}
			return
		}

		f.packets.Lock()
		f.packets.values = append(f.packets.values, readBuf[0:n])
		f.packets.Unlock()

		trans, _ := customtransport.NewTBufferedReadTransport(bytes.NewBuffer(readBuf[0:n]))
		var proto thrift.TProtocol
		if f.protocol == Compact {
			proto = thrift.NewTCompactProtocol(trans)
		} else {
			proto = thrift.NewTBinaryProtocolTransport(trans)
		}

		_, err = f.processor.Process(proto, proto)
		if terr, ok := err.(thrift.TTransportException); ok {
			require.Equal(f.t, thrift.END_OF_FILE, terr.TypeId())
		} else {
			require.NoError(f.t, err)
		}
	}
}

func (f *fakeM3Server) Close() error {
	atomic.AddInt32(&f.closed, 1)
	return f.conn.Close()
}

func (f *fakeM3Server) Packets() [][]byte {
	f.packets.Lock()
	defer f.packets.Unlock()

	packets := make([][]byte, len(f.packets.values))
	copy(packets, f.packets.values)
	return packets
}

func newFakeM3Service(wg *sync.WaitGroup, countBatches bool) *fakeM3Service {
	return &fakeM3Service{wg: wg, countBatches: countBatches}
}

type fakeM3Service struct {
	lock         sync.RWMutex
	batches      []m3thrift.MetricBatch
	metrics      []m3thrift.Metric
	wg           *sync.WaitGroup
	countBatches bool
}

func (m *fakeM3Service) getBatches() []m3thrift.MetricBatch {
	m.lock.RLock()
	defer m.lock.RUnlock()
	return m.batches
}

func (m *fakeM3Service) getMetrics() []m3thrift.Metric {
	m.lock.RLock()
	defer m.lock.RUnlock()
	return m.metrics
}

func (m *fakeM3Service) EmitMetricBatchV2(batch m3thrift.MetricBatch) (err error) {
	m.lock.Lock()
	m.batches = append(m.batches, batch)
	if m.wg != nil && m.countBatches {
		m.wg.Done()
	}

	for _, metric := range batch.Metrics {
		m.metrics = append(m.metrics, metric)
		if m.wg != nil && !m.countBatches {
			m.wg.Done()
		}
	}

	m.lock.Unlock()
	return thrift.NewTTransportException(thrift.END_OF_FILE, "complete")
}

func hostname() string {
	host, err := os.Hostname()
	if err != nil {
		host = "unknown"
	}
	return host
}

func tagIncluded(tags []m3thrift.MetricTag, tagName string) bool {
	for _, tag := range tags {
		if tag.Name == tagName {
			return true
		}
	}
	return false
}

func tagEquals(tags []m3thrift.MetricTag, tagName string, tagValue string) bool {
	for _, tag := range tags {
		if tag.GetName() == tagName && tag.GetValue() == tagValue {
			return true
		}
	}
	return false
}


text:
module Basecamp
  class PostCategory < Record
    class << self
      # Returns the list of message categories for the given project
      def list(project_id)
        records "/projects/#{project_id}/post_categories"
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
package openshift

import (
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"

	docker "github.com/fsouza/go-dockerclient"
	"github.com/golang/glog"
	"k8s.io/kubernetes/pkg/util/homedir"

	"github.com/openshift/origin/pkg/bootstrap/docker/dockerhelper"
	"github.com/openshift/origin/pkg/bootstrap/docker/errors"
	dockerexec "github.com/openshift/origin/pkg/bootstrap/docker/exec"
	"github.com/openshift/origin/pkg/bootstrap/docker/host"
	"github.com/openshift/origin/pkg/bootstrap/docker/run"
	cliconfig "github.com/openshift/origin/pkg/cmd/cli/config"
	configapi "github.com/openshift/origin/pkg/cmd/server/api"
	_ "github.com/openshift/origin/pkg/cmd/server/api/install"
	configapilatest "github.com/openshift/origin/pkg/cmd/server/api/latest"
	cmdutil "github.com/openshift/origin/pkg/cmd/util"
)

const (
	initialStatusCheckWait = 4 * time.Second
	serverUpTimeout        = 35
	serverConfigPath       = "/var/lib/origin/openshift.local.config"
	serverMasterConfig     = serverConfigPath + "/master/master-config.yaml"
	DefaultDNSPort         = 53
	AlternateDNSPort       = 8053
	cmdDetermineNodeHost   = "for name in %s; do ls /var/lib/origin/openshift.local.config/node-$name &> /dev/null && echo $name && break; done"
	OpenShiftContainer     = "origin"
)

var (
	openShiftContainerBinds = []string{
		"/var/log:/var/log:rw",
		"/var/run:/var/run:rw",
		"/sys:/sys:ro",
		"/var/lib/docker:/var/lib/docker",
	}
	BasePorts             = []int{4001, 7001, 8443, 10250}
	RouterPorts           = []int{80, 443}
	DefaultPorts          = append(BasePorts, DefaultDNSPort)
	PortsWithAlternateDNS = append(BasePorts, AlternateDNSPort)
	AllPorts              = append(append(RouterPorts, DefaultPorts...), AlternateDNSPort)
	SocatPidFile          = filepath.Join(homedir.HomeDir(), cliconfig.OpenShiftConfigHomeDir, "socat-8443.pid")
)

// Helper contains methods and utilities to help with OpenShift startup
type Helper struct {
	hostHelper    *host.HostHelper
	dockerHelper  *dockerhelper.Helper
	execHelper    *dockerexec.ExecHelper
	runHelper     *run.RunHelper
	client        *docker.Client
	publicHost    string
	image         string
	containerName string
	routingSuffix string
}

// StartOptions represent the parameters sent to the start command
type StartOptions struct {
	ServerIP           string
	RouterIP           string
	DNSPort            int
	UseSharedVolume    bool
	SetPropagationMode bool
	Images             string
	HostVolumesDir     string
	HostConfigDir      string
	HostDataDir        string
	UseExistingConfig  bool
	Environment        []string
	LogLevel           int
	MetricsHost        string
	LoggingHost        string
	PortForwarding     bool
}

// NewHelper creates a new OpenShift helper
func NewHelper(client *docker.Client, hostHelper *host.HostHelper, image, containerName, publicHostname, routingSuffix string) *Helper {
	return &Helper{
		client:        client,
		dockerHelper:  dockerhelper.NewHelper(client, nil),
		execHelper:    dockerexec.NewExecHelper(client, containerName),
		hostHelper:    hostHelper,
		runHelper:     run.NewRunHelper(client),
		image:         image,
		containerName: containerName,
		publicHost:    publicHostname,
		routingSuffix: routingSuffix,
	}
}

func (h *Helper) TestPorts(ports []int) error {
	portData, _, _, err := h.runHelper.New().Image(h.image).
		DiscardContainer().
		Privileged().
		HostNetwork().
		HostPid().
		Entrypoint("/bin/bash").
		Command("-c", "cat /proc/net/tcp && ( [ -e /proc/net/tcp6 ] && cat /proc/net/tcp6 || true)").
		Output()
	if err != nil {
		return errors.NewError("Cannot get TCP port information from Kubernetes host").WithCause(err)
	}
	return checkPortsInUse(portData, ports)
}

func testIPDial(ip string) error {
	// Attempt to connect to test container
	testHost := fmt.Sprintf("%s:8443", ip)
	glog.V(4).Infof("Attempting to dial %s", testHost)
	if err := cmdutil.WaitForSuccessfulDial(false, "tcp", testHost, 200*time.Millisecond, 1*time.Second, 10); err != nil {
		glog.V(2).Infof("Dial error: %v", err)
		return err
	}
	glog.V(4).Infof("Successfully dialed %s", testHost)
	return nil
}

func (h *Helper) TestIP(ip string) error {

	// Start test server on host
	id, err := h.runHelper.New().Image(h.image).
		Privileged().
		HostNetwork().
		Entrypoint("socat").
		Command("TCP-LISTEN:8443,crlf,reuseaddr,fork", "SYSTEM:\"echo 'hello world'\"").Start()
	if err != nil {
		return errors.NewError("cannot start simple server on Docker host").WithCause(err)
	}
	defer func() {
		errors.LogError(h.dockerHelper.StopAndRemoveContainer(id))
	}()
	return testIPDial(ip)
}

func (h *Helper) TestForwardedIP(ip string) error {
	// Start test server on host
	id, err := h.runHelper.New().Image(h.image).
		PortForward(8443, 8443).
		Entrypoint("socat").
		Command("TCP-LISTEN:8443,crlf,reuseaddr,fork", "SYSTEM:\"echo 'hello world'\"").Start()
	if err != nil {
		return errors.NewError("cannot start simple server on Docker host").WithCause(err)
	}
	defer func() {
		errors.LogError(h.dockerHelper.StopAndRemoveContainer(id))
	}()
	return testIPDial(ip)
}

func (h *Helper) DetermineNodeHost(hostConfigDir string, names ...string) (string, error) {
	result, _, _, err := h.runHelper.New().Image(h.image).
		DiscardContainer().
		Privileged().
		HostNetwork().
		Entrypoint("/bin/bash").
		Bind(fmt.Sprintf("%s:/var/lib/origin/openshift.local.config", hostConfigDir)).
		Command("-c", fmt.Sprintf(cmdDetermineNodeHost, strings.Join(names, " "))).Output()
	if err != nil {
		return "", err
	}
	return strings.TrimSpace(result), nil
}

// ServerIP retrieves the Server ip through the openshift start command
func (h *Helper) ServerIP() (string, error) {
	result, _, _, err := h.runHelper.New().Image(h.image).
		DiscardContainer().
		Privileged().
		HostNetwork().
		Command("start", "--print-ip").Output()
	if err != nil {
		return "", err
	}
	return strings.TrimSpace(result), nil
}

// OtherIPs tries to find other IPs besides the argument IP for the Docker host
func (h *Helper) OtherIPs(excludeIP string) ([]string, error) {
	result, _, _, err := h.runHelper.New().Image(h.image).
		DiscardContainer().
		Privileged().
		HostNetwork().
		Entrypoint("hostname").
		Command("-I").Output()
	if err != nil {
		return nil, err
	}

	candidates := strings.Split(result, " ")
	resultIPs := []string{}
	for _, ip := range candidates {
		if ip != excludeIP && !strings.Contains(ip, ":") { // for now, ignore IPv6
			resultIPs = append(resultIPs, ip)
		}
	}
	return resultIPs, nil
}

// Start starts the OpenShift master as a Docker container
// and returns a directory in the local file system where
// the OpenShift configuration has been copied
func (h *Helper) Start(opt *StartOptions, out io.Writer) (string, error) {
	// Ensure that socat is available locally
	if opt.PortForwarding {
		err := CheckSocat()
		if err != nil {
			return "", err
		}
	}

	binds := openShiftContainerBinds
	env := []string{}
	if opt.UseSharedVolume {
		binds = append(binds, fmt.Sprintf("%[1]s:%[1]s:shared", opt.HostVolumesDir))
		env = append(env, "OPENSHIFT_CONTAINERIZED=false")
	} else {
		binds = append(binds, "/:/rootfs:ro")
		propagationMode := ""
		if opt.SetPropagationMode {
			propagationMode = ":rslave"
		}
		binds = append(binds, fmt.Sprintf("%[1]s:%[1]s%[2]s", opt.HostVolumesDir, propagationMode))
	}
	env = append(env, opt.Environment...)
	binds = append(binds, fmt.Sprintf("%s:/var/lib/origin/openshift.local.config:z", opt.HostConfigDir))

	// Kubelet needs to be able to write to
	// /sys/devices/virtual/net/vethXXX/brport/hairpin_mode, so make this rw, not ro.
	binds = append(binds, "/sys/devices/virtual/net:/sys/devices/virtual/net:rw")

	// Check if a configuration exists before creating one if UseExistingConfig
	// was specified
	var configDir string
	cleanupConfig := func() {
		errors.LogError(os.RemoveAll(configDir))
	}
	skipCreateConfig := false
	if opt.UseExistingConfig {
		var err error
		configDir, err = h.copyConfig()
		if err == nil {
			_, err = os.Stat(filepath.Join(configDir, "master", "master-config.yaml"))
			if err == nil {
				skipCreateConfig = true
			}
		}
	}

	// Create configuration if needed
	var nodeHost string
	if !skipCreateConfig {
		fmt.Fprintf(out, "Creating initial OpenShift configuration\n")
		createConfigCmd := []string{
			"start",
			fmt.Sprintf("--images=%s", opt.Images),
			fmt.Sprintf("--volume-dir=%s", opt.HostVolumesDir),
			fmt.Sprintf("--dns=0.0.0.0:%d", opt.DNSPort),
			"--write-config=/var/lib/origin/openshift.local.config",
		}
		if opt.PortForwarding {
			internalIP, err := h.ServerIP()
			if err != nil {
				return "", err
			}
			nodeHost = internalIP
			createConfigCmd = append(createConfigCmd, fmt.Sprintf("--master=%s", internalIP))
			createConfigCmd = append(createConfigCmd, fmt.Sprintf("--public-master=https://%s:8443", opt.ServerIP))
		} else {
			nodeHost = opt.ServerIP
			createConfigCmd = append(createConfigCmd, fmt.Sprintf("--master=%s", opt.ServerIP))
			if len(h.publicHost) > 0 {
				createConfigCmd = append(createConfigCmd, fmt.Sprintf("--public-master=https://%s:8443", h.publicHost))
			}
		}
		createConfigCmd = append(createConfigCmd, fmt.Sprintf("--hostname=%s", nodeHost))
		_, err := h.runHelper.New().Image(h.image).
			Privileged().
			DiscardContainer().
			HostNetwork().
			HostPid().
			Bind(binds...).
			Env(env...).
			Command(createConfigCmd...).Run()
		if err != nil {
			return "", errors.NewError("could not create OpenShift configuration").WithCause(err)
		}
		configDir, err = h.copyConfig()
		if err != nil {
			return "", errors.NewError("could not copy OpenShift configuration").WithCause(err)
		}
		err = h.updateConfig(configDir, opt.RouterIP, opt.MetricsHost, opt.LoggingHost)
		if err != nil {
			cleanupConfig()
			return "", errors.NewError("could not update OpenShift configuration").WithCause(err)
		}
	}
	if nodeHost == "" {
		if opt.PortForwarding {
			var err error
			nodeHost, err = h.ServerIP()
			if err != nil {
				return "", err
			}
		} else {
			var err error
			hostName, err := h.hostHelper.Hostname()
			if err != nil {
				return "", err
			}
			nodeHost, err = h.DetermineNodeHost(opt.HostConfigDir, opt.ServerIP, hostName)
			if err != nil {
				return "", err
			}
		}
	}
	masterConfig, nodeConfig, err := h.getOpenShiftConfigFiles(nodeHost)
	if err != nil {
		cleanupConfig()
		return "", errors.NewError("could not get OpenShift configuration file paths").WithCause(err)
	}

	fmt.Fprintf(out, "Starting OpenShift using container '%s'\n", h.containerName)
	startCmd := []string{
		"start",
		fmt.Sprintf("--master-config=%s", masterConfig),
		fmt.Sprintf("--node-config=%s", nodeConfig),
	}
	if opt.LogLevel > 0 {
		startCmd = append(startCmd, fmt.Sprintf("--loglevel=%d", opt.LogLevel))
	}

	if opt.PortForwarding {
		err = h.startSocatTunnel()
		if err != nil {
			return "", err
		}
	}

	if len(opt.HostDataDir) > 0 {
		binds = append(binds, fmt.Sprintf("%s:/var/lib/origin/openshift.local.etcd:z", opt.HostDataDir))
	}
	_, err = h.runHelper.New().Image(h.image).
		Name(h.containerName).
		Privileged().
		HostNetwork().
		HostPid().
		Bind(binds...).
		Env(env...).
		Command(startCmd...).
		Start()
	if err != nil {
		return "", errors.NewError("cannot start OpenShift daemon").WithCause(err)
	}

	// Wait a minimum amount of time and check whether we're still running. If not, we know the daemon didn't start
	time.Sleep(initialStatusCheckWait)
	_, running, err := h.dockerHelper.GetContainerState(h.containerName)
	if err != nil {
		return "", errors.NewError("cannot get state of OpenShift container %s", h.containerName).WithCause(err)
	}
	if !running {
		return "", ErrOpenShiftFailedToStart(h.containerName).WithDetails(h.OriginLog())
	}

	// Wait until the API server is listening
	fmt.Fprintf(out, "Waiting for API server to start listening\n")
	masterHost := fmt.Sprintf("%s:8443", opt.ServerIP)
	if err = cmdutil.WaitForSuccessfulDial(true, "tcp", masterHost, 200*time.Millisecond, 1*time.Second, serverUpTimeout); err != nil {
		return "", errors.NewError("timed out waiting for OpenShift container %q \nWARNING: %s:8443 may be blocked by firewall rules", h.containerName, opt.ServerIP).WithSolution("Ensure that you can access %s from your machine", masterHost).WithDetails(h.OriginLog())
	}
	// Check for healthz endpoint to be ready
	client, err := masterHTTPClient(configDir)
	if err != nil {
		return "", err
	}
	for {
		resp, ierr := client.Get(h.healthzReadyURL(opt.ServerIP))
		if ierr != nil {
			return "", errors.NewError("cannot access master readiness URL %s", h.healthzReadyURL(opt.ServerIP)).WithCause(err).WithDetails(h.OriginLog())
		}
		if resp.StatusCode == http.StatusOK {
			break
		}
		if resp.StatusCode == http.StatusServiceUnavailable ||
			resp.StatusCode == http.StatusForbidden {
			time.Sleep(500 * time.Millisecond)
			continue
		}
		var responseBody string
		body, rerr := ioutil.ReadAll(resp.Body)
		if rerr == nil {
			responseBody = string(body)
		}
		return "", errors.NewError("server is not ready. Response (%d): %s", resp.StatusCode, responseBody).WithCause(ierr).WithDetails(h.OriginLog())
	}
	fmt.Fprintf(out, "OpenShift server started\n")
	return configDir, nil
}

func (h *Helper) OriginLog() string {
	log := h.dockerHelper.ContainerLog(h.containerName, 10)
	if len(log) > 0 {
		return fmt.Sprintf("Last 10 lines of %q container log:\n%s\n", h.containerName, log)
	}
	return fmt.Sprintf("No log available from %q container\n", h.containerName)
}

func (h *Helper) healthzReadyURL(ip string) string {
	return fmt.Sprintf("%s/healthz/ready", h.Master(ip))
}

func (h *Helper) Master(ip string) string {
	return fmt.Sprintf("https://%s:8443", ip)
}

func masterHTTPClient(localConfig string) (*http.Client, error) {
	caCert := filepath.Join(localConfig, "master", "ca.crt")
	transport, err := cmdutil.TransportFor(caCert, "", "")
	if err != nil {
		return nil, err
	}
	return &http.Client{
		Transport: transport,
		Timeout:   10 * time.Second,
	}, nil
}

// copyConfig copies the OpenShift configuration directory from the
// server directory into a local temporary directory.
func (h *Helper) copyConfig() (string, error) {
	tempDir, err := ioutil.TempDir("", "openshift-config")
	if err != nil {
		return "", err
	}
	glog.V(1).Infof("Copying OpenShift config to local directory %s", tempDir)
	if err = h.hostHelper.DownloadDirFromContainer(serverConfigPath, tempDir); err != nil {
		if removeErr := os.RemoveAll(tempDir); removeErr != nil {
			glog.V(2).Infof("Error removing temporary config dir %s: %v", tempDir, removeErr)
		}
		return "", err
	}

	return tempDir, nil
}

func (h *Helper) GetConfigFromLocalDir(configDir string) (*configapi.MasterConfig, string, error) {
	configPath := filepath.Join(configDir, "master", "master-config.yaml")
	glog.V(1).Infof("Reading master config from %s", configPath)
	cfg, err := configapilatest.ReadMasterConfig(configPath)
	if err != nil {
		glog.V(1).Infof("Could not read master config: %v", err)
		return nil, "", err
	}
	return cfg, configPath, nil
}

func GetConfigFromContainer(client *docker.Client) (*configapi.MasterConfig, error) {
	r, err := dockerhelper.StreamFileFromContainer(client, OpenShiftContainer, serverMasterConfig)
	if err != nil {
		return nil, err
	}
	defer r.Close()

	data, err := ioutil.ReadAll(r)
	if err != nil {
		return nil, err
	}
	config := &configapi.MasterConfig{}
	err = configapilatest.ReadYAMLInto(data, config)
	if err != nil {
		return nil, err
	}
	return config, nil
}

func (h *Helper) updateConfig(configDir, routerIP, metricsHost, loggingHost string) error {
	cfg, configPath, err := h.GetConfigFromLocalDir(configDir)
	if err != nil {
		return err
	}

	if len(h.routingSuffix) > 0 {
		cfg.RoutingConfig.Subdomain = h.routingSuffix
	} else {
		cfg.RoutingConfig.Subdomain = fmt.Sprintf("%s.xip.io", routerIP)
	}

	if len(metricsHost) > 0 && cfg.AssetConfig != nil {
		cfg.AssetConfig.MetricsPublicURL = fmt.Sprintf("https://%s/hawkular/metrics", metricsHost)
	}

	if len(loggingHost) > 0 && cfg.AssetConfig != nil {
		cfg.AssetConfig.LoggingPublicURL = fmt.Sprintf("https://%s", loggingHost)
	}

	cfgBytes, err := configapilatest.WriteYAML(cfg)
	if err != nil {
		return err
	}
	err = ioutil.WriteFile(configPath, cfgBytes, 0644)
	if err != nil {
		return err
	}
	return h.hostHelper.UploadFileToContainer(configPath, serverMasterConfig)
}

func (h *Helper) getOpenShiftConfigFiles(hostname string) (string, string, error) {
	return serverMasterConfig,
		fmt.Sprintf("/var/lib/origin/openshift.local.config/node-%s/node-config.yaml", hostname),
		nil
}

func checkPortsInUse(data string, ports []int) error {
	used := getUsedPorts(data)
	conflicts := []int{}
	for _, port := range ports {
		if _, inUse := used[port]; inUse {
			conflicts = append(conflicts, port)
		}
	}
	if len(conflicts) > 0 {
		return ErrPortsNotAvailable(conflicts)
	}
	return nil
}

func getUsedPorts(data string) map[int]struct{} {
	ports := map[int]struct{}{}
	lines := strings.Split(data, "\n")
	for _, line := range lines {
		parts := strings.Fields(line)
		if len(parts) < 2 {
			continue
		}
		// discard lines that don't contain connection data
		if !strings.Contains(parts[0], ":") {
			continue
		}
		glog.V(5).Infof("Determining port in use from: %s", line)
		localAddress := strings.Split(parts[1], ":")
		if len(localAddress) < 2 {
			continue
		}
		state := parts[3]
		if state != "0A" { // only look at connections that are listening
			continue
		}
		port, err := strconv.ParseInt(localAddress[1], 16, 0)
		if err == nil {
			ports[int(port)] = struct{}{}
		}
	}
	glog.V(2).Infof("Used ports in container: %#v", ports)
	return ports
}


text:
var assert = require("assert");
var path = require("path");
var local = path.join.bind(path, __dirname);

describe("Cred", function() {
  var NodeGit = require("../../");

  var sshPublicKey = local("../id_rsa.pub");
  var sshPrivateKey = local("../id_rsa");

  it("can create default credentials", function() {
    var defaultCreds = NodeGit.Cred.defaultNew();
    assert.ok(defaultCreds instanceof NodeGit.Cred);
  });

  it("can create ssh credentials using passed keys", function() {
    var cred = NodeGit.Cred.sshKeyNew(
      "username",
      sshPublicKey,
      sshPrivateKey,
      "");

    assert.ok(cred instanceof NodeGit.Cred);
  });

  it("can create credentials using plaintext", function() {
    var plaintextCreds = NodeGit.Cred.userpassPlaintextNew
      ("username", "password");
    assert.ok(plaintextCreds instanceof NodeGit.Cred);
  });
});


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using TravelAlbum.Models;
using TravelAlbum.Resources.App_GlobalResources;
using TravelAlbum.Web.Enums;

namespace TravelAlbum.Web.Models.ImageModels
{
    public class ImagesListViewModel
    {
        // private ICollection<Mountain> mountains;

        public ImagesListViewModel()
        {
            this.ImagePreviews = new List<ImagePreviewOutputViewModel>();
            // this.Mountains = new HashSet<Mountain>();
            // this.Mountains = new HashSet<Mountains>();
        }

        [Display(Name = "Search")]
        public string SearchedTitle { get; set; }

        [Display(Name = "MountainSearchLabel", ResourceType = typeof(GlobalResources))]
        public IEnumerable<Guid> MountainsIds { get; set; }

        public IEnumerable<SelectListItem> MountainsDropDown { get; set; }

        public List<ImagePreviewOutputViewModel> ImagePreviews { get; set; }

        public Sorting SelectedSorting { get; set; }

        public int SelectedPageSize { get; set; }

        public IEnumerable<SelectListItem> PageSizes { get; set; }

        public int CurrentPage { get; set; }

        public int TotalPages { get; set; }

        public string BackgroundData { get; set; }
    }
}


text:
<?php

declare(strict_types=1);

namespace ApiPlatform\Tests\Fixtures\TestBundle\Document;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use Symfony\Component\Serializer\Annotation\Groups;

#[ODM\MappedSuperclass]
abstract class VoDummyVehicle
{
    use VoDummyIdAwareTrait;
    /**
     * @var Collection<VoDummyDriver>
     */
    #[Groups(['car_read', 'car_write'])]
    #[ODM\ReferenceMany(targetDocument: VoDummyDriver::class, cascade: ['persist'])]
    private Collection $drivers;

    public function __construct(
        #[Groups(['car_read', 'car_write'])] #[ODM\Field] private string $make,
        #[Groups(['car_read', 'car_write'])] #[ODM\ReferenceOne(targetDocument: VoDummyInsuranceCompany::class, cascade: ['persist'])] private VoDummyInsuranceCompany $insuranceCompany,
        array $drivers
    ) {
        $this->drivers = new ArrayCollection($drivers);
    }

    public function getMake()
    {
        return $this->make;
    }

    public function getInsuranceCompany()
    {
        return $this->insuranceCompany;
    }

    /**
     * @return Collection<VoDummyDriver>
     */
    public function getDrivers()
    {
        return $this->drivers;
    }
}


text:
__author__ = 'justasic'
from NutmegCRM.apps.crm.models import Customer
from NutmegCRM.apps.tickets.models import Ticket

def search_helper(count, query):
    import itertools
    model_list = Customer.objects.filter(title__icontains=query, status=1)

    for L in range(1, count+1):
        for subset in itertools.permutations(query, L):
            count1 = 1
            query1 = subset[0]
            while count1 != len(subset):
                query1 = query1 + " " + subset[count1]
                count1 += 1
            model_list = Customer.objects.filter(title__icontains=query1, status=1)

    return model_list.distinct()


text:
require 'puppet/ssl'

# The tedious class that does all the manipulations to the
# certificate to correctly sign it.  Yay.
module Puppet::SSL::CertificateFactory
  def self.build(cert_type, csr, issuer, serial, ttl = nil)
    # Work out if we can even build the requested type of certificate.
    build_extensions = "build_#{cert_type.to_s}_extensions"
    respond_to?(build_extensions) or
      raise ArgumentError, "#{cert_type.to_s} is an invalid certificate type!"

    raise ArgumentError, "Certificate TTL must be an integer" unless ttl.nil? || ttl.is_a?(Fixnum)

    # set up the certificate, and start building the content.
    cert = OpenSSL::X509::Certificate.new

    cert.version    = 2 # X509v3
    cert.subject    = csr.content.subject
    cert.issuer     = issuer.subject
    cert.public_key = csr.content.public_key
    cert.serial     = serial

    # Make the certificate valid as of yesterday, because so many people's
    # clocks are out of sync.  This gives one more day of validity than people
    # might expect, but is better than making every person who has a messed up
    # clock fail, and better than having every cert we generate expire a day
    # before the user expected it to when they asked for "one year".
    cert.not_before = Time.now - (60*60*24)
    cert.not_after  = Time.now + (ttl || Puppet[:ca_ttl])

    add_extensions_to(cert, csr, issuer, send(build_extensions))

    return cert
  end

  private

  def self.add_extensions_to(cert, csr, issuer, extensions)
    ef = OpenSSL::X509::ExtensionFactory.
      new(cert, issuer.is_a?(OpenSSL::X509::Request) ? cert : issuer)

    # Extract the requested extensions from the CSR.
    requested_exts = csr.request_extensions.inject({}) do |hash, re|
      hash[re["oid"]] = [re["value"], re["critical"]]
      hash
    end

    # Produce our final set of extensions.  We deliberately order these to
    # build the way we want:
    # 1. "safe" default values, like the comment, that no one cares about.
    # 2. request extensions, from the CSR
    # 3. extensions based on the type we are generating
    # 4. overrides, which we always want to have in their form
    #
    # This ordering *is* security-critical, but we want to allow the user
    # enough rope to shoot themselves in the foot, if they want to ignore our
    # advice and externally approve a CSR that sets the basicConstraints.
    #
    # Swapping the order of 2 and 3 would ensure that you couldn't slip a
    # certificate through where the CA constraint was true, though, if
    # something went wrong up there. --daniel 2011-10-11
    defaults = { "nsComment" => "Puppet Ruby/OpenSSL Internal Certificate" }
    override = { "subjectKeyIdentifier" => "hash" }

    exts = [defaults, requested_exts, extensions, override].
      inject({}) {|ret, val| ret.merge(val) }

    cert.extensions = exts.map do |oid, val|
      generate_extension(ef, oid, *val)
    end
  end

  # Woot! We're a CA.
  def self.build_ca_extensions
    {
      # This was accidentally omitted in the previous version of this code: an
      # effort was made to add it last, but that actually managed to avoid
      # adding it to the certificate at all.
      #
      # We have some sort of bug, which means that when we add it we get a
      # complaint that the issuer keyid can't be fetched, which breaks all
      # sorts of things in our test suite and, e.g., bootstrapping the CA.
      #
      # http://tools.ietf.org/html/rfc5280#section-4.2.1.1 says that, to be a
      # conforming CA we MAY omit the field if we are self-signed, which I
      # think gives us a pass in the specific case.
      #
      # It also notes that we MAY derive the ID from the subject and serial
      # number of the issuer, or from the key ID, and we definitely have the
      # former data, should we want to restore this...
      #
      # Anyway, preserving this bug means we don't risk breaking anything in
      # the field, even though it would be nice to have. --daniel 2011-10-11
      #
      # "authorityKeyIdentifier" => "keyid:always,issuer:always",
      "keyUsage"               => [%w{cRLSign keyCertSign}, true],
      "basicConstraints"       => ["CA:TRUE", true],
    }
  end

  # We're a terminal CA, probably not self-signed.
  def self.build_terminalsubca_extensions
    {
      "keyUsage"         => [%w{cRLSign keyCertSign}, true],
      "basicConstraints" => ["CA:TRUE,pathlen:0", true],
    }
  end

  # We're a normal server.
  def self.build_server_extensions
    {
      "keyUsage"         => [%w{digitalSignature keyEncipherment}, true],
      "extendedKeyUsage" => [%w{serverAuth clientAuth}, true],
      "basicConstraints" => ["CA:FALSE", true],
    }
  end

  # Um, no idea.
  def self.build_ocsp_extensions
    {
      "keyUsage"         => [%w{nonRepudiation digitalSignature}, true],
      "extendedKeyUsage" => [%w{serverAuth OCSPSigning}, true],
      "basicConstraints" => ["CA:FALSE", true],
    }
  end

  # Normal client.
  def self.build_client_extensions
    {
      "keyUsage"         => [%w{nonRepudiation digitalSignature keyEncipherment}, true],
      # We don't seem to use this, but that seems much more reasonable here...
      "extendedKeyUsage" => [%w{clientAuth emailProtection}, true],
      "basicConstraints" => ["CA:FALSE", true],
      "nsCertType"       => "client,email",
    }
  end

  # Generate an extension with the given OID, value, and critical state
  #
  # @param oid [String] The numeric value or short name of a given OID. X509v3
  #   extensions must be passed by short name or long name, while custom
  #   extensions may be passed by short name, long name, oid numeric OID.
  # @param ef [OpenSSL::X509::ExtensionFactory] The extension factory to use
  #   when generating the extension.
  # @param val [String, Array<String>] The extension value.
  # @param crit [true, false] Whether the given extension is critical, defaults
  #   to false.
  #
  # @return [OpenSSL::X509::Extension]
  #
  # @api private
  def self.generate_extension(ef, oid, val, crit = false)

    val = val.join(', ') unless val.is_a? String

    # Enforce the X509v3 rules about subjectAltName being critical:
    # specifically, it SHOULD NOT be critical if we have a subject, which we
    # always do. --daniel 2011-10-18
    crit = false if oid == "subjectAltName"

    if Puppet::SSL::Oids.subtree_of?('id-ce', oid) or Puppet::SSL::Oids.subtree_of?('id-pkix', oid)
      # Attempt to create a X509v3 certificate extension. Standard certificate
      # extensions may need access to the associated subject certificate and
      # issuing certificate, so must be created by the OpenSSL::X509::ExtensionFactory
      # which provides that context.
      ef.create_ext(oid, val, crit)
    else
      # This is not an X509v3 extension which means that the extension
      # factory cannot generate it. We need to generate the extension
      # manually.
      OpenSSL::X509::Extension.new(oid, val, crit)
    end
  end
end


text:
import { AnimationPlayer, AnimationTriggerMetadata } from '@angular/animations';
import { AnimationEngine } from '../animation_engine';
export declare class NoopAnimationEngine extends AnimationEngine {
    private _listeners;
    private _changes;
    private _flaggedRemovals;
    private _onDoneFns;
    private _triggerStyles;
    registerTrigger(trigger: AnimationTriggerMetadata, name?: string): void;
    onInsert(element: any, domFn: () => any): void;
    onRemove(element: any, domFn: () => any): void;
    setProperty(element: any, property: string, value: any): void;
    listen(element: any, eventName: string, eventPhase: string, callback: (event: any) => any): () => any;
    flush(): void;
    readonly activePlayers: AnimationPlayer[];
    readonly queuedPlayers: AnimationPlayer[];
}


text:
using namespace boost::interprocess;

int main ()
{
   try{
      //Remove shared memory on construction and destruction
      struct shm_remove
      {
         shm_remove() { shared_memory_object::remove("MySharedMemory"); }
         ~shm_remove(){ shared_memory_object::remove("MySharedMemory"); }
      } remover;
      //<-
      (void)remover;
      //->

      //Create a shared memory object.
      shared_memory_object shm
         (create_only               //only create
         ,"MySharedMemory"          //name
         ,read_write   //read-write mode
         );

      //Set size
      shm.truncate(sizeof(shared_memory_log));

      //Map the whole shared memory in this process
      mapped_region region
         (shm                       //What to map
         ,read_write   //Map it as read-write
         );

      //Get the address of the mapped region
      void * addr       = region.get_address();

      //Construct the shared structure in memory
      shared_memory_log * data = new (addr) shared_memory_log;

      //Write some logs
      for(int i = 0; i < shared_memory_log::NumItems; ++i){
         //Lock the mutex
         scoped_lock<interprocess_mutex> lock(data->mutex);
         std::sprintf(data->items[(data->current_line++) % shared_memory_log::NumItems]
                  ,"%s_%d", "process_a", i);
         if(i == (shared_memory_log::NumItems-1))
            data->end_a = true;
         //Mutex is released here
      }

      //Wait until the other process ends
      while(1){
         scoped_lock<interprocess_mutex> lock(data->mutex);
         if(data->end_b)
            break;
      }
   }
   catch(interprocess_exception &ex){
      std::cout << ex.what() << std::endl;
      return 1;
   }
   return 0;
}
//]
#include <boost/interprocess/detail/config_end.hpp>


text:
package vision

import "testing"

func TestParseString(t *testing.T) {
	text := "Hello World"
	str, err := ParseString(text)
	if err != nil {
		t.Fatalf("Unable to parse text result. Error: %v", err.Error())
	}
	if str.String() != text {
		t.Fatalf("Unexpected string result. Found %v, expected %v", str, text)
	}
}

func TestStringValue(t *testing.T) {
	expected := "Hello World"
	text := String(expected)
	if text.String() != expected {
		t.Fatalf("Unexpected string result. Found %v, expected %v", text, expected)
	}
}

func TestStringToInteger(t *testing.T) {
	num := 1
	str, err := ParseString(num)
	if err != nil {
		t.Fatalf("Unable to parse integer value. Error: %v", err.Error())
	}
	if int(str.Integer()) != num {
		t.Fatalf("Unexpected string result. Found %d, expected %d", str.Integer(), num)
	}
}

func TestStringToFloat(t *testing.T) {
	num := 1.2
	str, err := ParseString(num)
	if err != nil {
		t.Fatalf("Unable to parse float value. Error: %v", err.Error())
	}
	if float64(str.Float()) != num {
		t.Fatalf("Unexpected string result. Found %f, expected %f", str.Float(), num)
	}
}

func TestStringToBoolTrue(t *testing.T) {
	res := true
	str, err := ParseString(res)
	if err != nil {
		t.Fatalf("Unable to parse bool value. Error: %v", err.Error())
	}
	if bool(str.Bool()) != res {
		t.Fatalf("Unexpected string result. Found %v, expected %v", str.Bool(), res)
	}
}

func TestStringToBoolFalse(t *testing.T) {
	res := false
	str, err := ParseString(res)
	if err != nil {
		t.Fatalf("Unable to parse bool value. Error: %v", err.Error())
	}
	if bool(str.Bool()) != res {
		t.Fatalf("Unexpected string result. Found %v, expected %v", str.Bool(), res)
	}
}

func TestStringIsEmpty(t *testing.T) {
	text := String("")
	if text.IsEmpty() != true {
		t.Fatalf("Unexpected result to be empty. Found %v, expected %v", text.IsEmpty(), true)
	}
}

func TestWhitespaceStringIsEmpty(t *testing.T) {
	text := String(" ")
	if text.IsEmpty() {
		t.Fatalf("Unexpected result not to be empty. Found %v, expected %v", text.IsEmpty(), false)
	}
}

func TestStringMustEmpty(t *testing.T) {
	text := String(" ")
	if !text.MustEmpty() {
		t.Fatalf("Unexpected result to be empty. Found %v, expected %v", text.MustEmpty(), true)
	}
}

func TestStringIsLength(t *testing.T) {
	text := String("")
	if !text.IsLength(0, 1) {
		t.Fatalf("Unexpected result to be true. Found %v, expected %v", text.IsLength(0, 1), true)
	}
}

func TestWhitespaceStringIsLength(t *testing.T) {
	text := String(" ")
	if !text.IsLength(0, 1) {
		t.Fatalf("Unexpected result to be false. Found %v, expected %v", text.IsLength(0, 1), false)
	}
}

func TestWhitespaceStringMustLength(t *testing.T) {
	text := String(" /.")
	if !text.MustLength(0, 0) {
		t.Fatalf("Unexpected result to be true. Found %v, expected %v", text.MustLength(0, 0), true)
	}
}

func TestStringIsEmail(t *testing.T) {
	tests := map[string]bool{
		"localhost":           false,
		"127.0.0.1":           false,
		"test@localhost":      false,
		"awesome@example.com": true,
		"test@gmail.com":      true,
	}
	for v := range tests {
		expected := tests[v]
		if valid := String(v).IsEmail(); valid != expected {
			t.Fatalf("Unexpected result of checking valid email address. Found %v, expected %v", valid, expected)
		}
	}
}

func TestStringIsURL(t *testing.T) {
	tests := map[string]bool{
		"http://google.ca":    true,
		"127.0.0.1":           true,
		"gmail.com":           true,
		"https://example.com": true,
		"ftp://google.ca":     false,
		"localhost":           true,
	}
	for v := range tests {
		expected := tests[v]
		if valid := String(v).IsURL(); valid != expected {
			t.Fatalf("Unexpected result of checking valid URL %v. Found %v, expected %v", v, valid, expected)
		}
	}
}


text:
* Ability to change configuration from inside the interface.
* Remove every need to reboot except for absolute crashes.
* An app launcher for Mac, a 'better' launcher for Windows (icons etc.)
* Pack with nexe as a single executable (still needs some research).
* Create folders, upload files, insert predefined empties, and create server editions with full configuration.
* Add a default `settings.json` to the repo that works so that it can be launched without needing to create it first.
* Add authentication.
* Add WebSockets that any file can make use of to build a chatroom or otherwise connect pages. Each file manages its own chatrooms or chatrooms can be declared in settings. A chatroom can be restricted to only allow certain URLs (although this can be circumverted by an attacker) or password protected. We could do private key encryption too if we wanted to. Or use a straight AES-256 end-to-end encryption with a preshared key, but the key could not be distributed by the server or it would not be secure.
** http://socketcluster.io
** https://github.com/sockjs/sockjs-node
** npm ws
* Add an admin page to manage settings, engines, and files, and add new files and data folders.
* Allow individual settings for tree mount paths such as credentials and backups.


text:
<?php

require_once __DIR__.'/Base.php';

use Event\TaskLinkEvent;
use Model\Task;
use Model\TaskCreation;
use Model\TaskFinder;
use Model\TaskLink;
use Model\Project;

class ActionTaskAssignColorLinkTest extends Base
{
    public function testExecute()
    {
        $action = new Action\TaskAssignColorLink($this->container, 1, TaskLink::EVENT_CREATE_UPDATE);
        $action->setParam('link_id', 2);
        $action->setParam('color_id', 'green');

        // We create a task in the first column
        $tc = new TaskCreation($this->container);
        $tf = new TaskFinder($this->container);
        $tl = new TaskLink($this->container);
        $p = new Project($this->container);
        $this->assertEquals(1, $p->create(array('name' => 'test')));
        $this->assertEquals(1, $tc->create(array('title' => 'test', 'project_id' => 1)));

        // The color should be yellow
        $task = $tf->getById(1);
        $this->assertNotEmpty($task);
        $this->assertEquals('yellow', $task['color_id']);

        $event = array(
            'project_id' => 1,
            'task_id' => 1,
            'link_id' => 2,
        );

        // Our event should be executed
        $this->assertTrue($action->execute(new TaskLinkEvent($event)));

        // The color should be green
        $task = $tf->getById(1);
        $this->assertNotEmpty($task);
        $this->assertEquals('green', $task['color_id']);
    }
}


text:
minio
=====

[Minio][1] is an object storage server released under Apache License v2.0. It is
compatible with Amazon S3 cloud storage service. It is best suited for storing
unstructured data such as photos, videos, log files, backups and container / VM
images. Size of an object can range from a few KBs to a maximum of 5TB.

Minio server is light enough to be bundled with the application stack, similar
to NodeJS, Redis and MySQL.

## docker-compose.yml

```yaml
minio:
  image: minio/minio
  command: server /data
  ports:
    - "9000:9000"
  volumes:
    - ./data:/data
    - ./conf:/root/.minio
  restart: always
```

## Server

```bash
$ docker-compose up -d
$ cat ./conf/config.json
# "accessKey": "XXXXXXXXXXXXXXXXXXXX",
# "secretKey": "YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY"
$ curl -u XXXXXXXXXXXXXXXXXXXX:YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY http://127.0.0.1:9000
```

## Client

Download minio client:

- [linux/amd64][2]
- [linux/386][3]
- [linux/arm][4]

Read minio [tutorial][5].

```bash
$ mc config host add minio http://127.0.0.1:9000 XXXXXXXXXXXXXXXXXXXX YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY
$ mc mb minio/test
$ mc cp README.md minio/test
$ mc cat minio/test/README.md
$ mc ls -r minio
$ mc rm minio/test/README.md
$ mc rm minio/test
```

## Client (Android)

```bash
$ termux-setup-storage
$ realpath ~/storage/dcim
/storage/emulated/0/DCIM
$ cd ~/storage/dcim/Camera
$ termux-camera-photo -c 0 back.jpg
$ termux-camera-photo -c 1 front.jpg

$ go get -u github.com/minio/mc
$ mc config host add minio http://127.0.0.1:9000 XXXXXXXXXXXXXXXXXXXX YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY
$ mc mb minio/android
$ mc mirror --force --remove --watch /storage/emulated/0/DCIM/Camera/ minio/android/camera
```

```bash
$ pwd
/data/data/com.termux/files/home

$ cat >> .bashrc << _EOF_
export TMPDIR=/data/data/com.termux/files/usr/tmp
export AWS_ACCESS_KEY_ID=XXXXXXXXXXXXXXXXXXXX
export AWS_SECRET_ACCESS_KEY=YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY
export RESTIC_REPOSITORY=s3:http://192.168.1.104:9000/android
export RESTIC_PASSWORD=ZZZZZZZZ
_EOF_

$ restic init
$ restic backup .bashrc
$ restic snapshots
ID        Date                 Host        Tags        Directory
----------------------------------------------------------------------
8d6a4777  2017-10-03 04:54:39  localhost               /data/data/com.termux/files/home/.bashrc

$ restic restore 8d6a4777 -t xxx
$ ls -al xxx
total 12
drwx------    2 u0_a120  u0_a120       4096 Oct  3 12:59 .
drwx------   14 u0_a120  u0_a120       4096 Oct  3 12:59 ..
-rw-------    1 u0_a120  u0_a120        406 Oct  3 12:53 .bashrc
$ rm -r xxx
```

[1]: https://minio.io/
[2]: https://dl.minio.io/client/mc/release/linux-amd64/mc
[3]: https://dl.minio.io/client/mc/release/linux-386/mc
[4]: https://dl.minio.io/client/mc/release/linux-arm/mc
[5]: https://docs.minio.io/docs/minio-client-quickstart-guide


text:
require File.expand_path(File.join(File.dirname(__FILE__),'..','..','..','test_helper'))

class NewRelic::Agent::Instrumentation::MetricFrameTest < Test::Unit::TestCase

  attr_reader :f
  def setup
    @f = NewRelic::Agent::Instrumentation::MetricFrame.new
  end

  def test_request_parsing__none
    assert_nil f.uri
    assert_nil f.referer
  end
  def test_request_parsing__path
    request = stub(:path => '/path?hello=bob#none')
    f.request = request
    assert_equal "/path", f.uri
  end
  def test_request_parsing__fullpath
    request = stub(:fullpath => '/path?hello=bob#none')
    f.request = request
    assert_equal "/path", f.uri
  end
  def test_request_parsing__referer
    request = stub(:referer => 'https://www.yahoo.com:8080/path/hello?bob=none&foo=bar')
    f.request = request
    assert_nil f.uri
    assert_equal "https://www.yahoo.com:8080/path/hello", f.referer
  end

  def test_request_parsing__uri
    request = stub(:uri => 'http://creature.com/path?hello=bob#none', :referer => '/path/hello?bob=none&foo=bar')
    f.request = request
    assert_equal "/path", f.uri
    assert_equal "/path/hello", f.referer
  end

  def test_request_parsing__hostname_only
    request = stub(:uri => 'http://creature.com')
    f.request = request
    assert_equal "/", f.uri
    assert_nil f.referer
  end
  def test_request_parsing__slash
    request = stub(:uri => 'http://creature.com/')
    f.request = request
    assert_equal "/", f.uri
    assert_nil f.referer
  end
end


text:
static constexpr auto COMPILER = "clang++";
#else
static constexpr auto COMPILER = "g++";
#endif

using namespace std;
using namespace rapidjson;

struct coordinate_t {
  double x;
  double y;
  double z;

  auto operator<=>(const coordinate_t &) const = default;

  friend ostream &operator<<(ostream &out, const coordinate_t &point) {
    out << "coordinate_t {x: " << point.x << ", y: " << point.y
        << ", z: " << point.z << "}";
    return out;
  }
};

using TCallback = function<void(const coordinate_t &)>;

class CoordinateHandler : public BaseReaderHandler<UTF8<>, CoordinateHandler> {
public:
  CoordinateHandler(const TCallback &callback)
      : state_(kStart), x_(), y_(), z_(), callback_(callback) {}

  bool Double(double d) {
    switch (state_) {
    case kX:
      x_ += d;
      state_ = kCoordinatesElement;
      break;
    case kY:
      y_ += d;
      state_ = kCoordinatesElement;
      break;
    case kZ:
      z_ += d;
      state_ = kCoordinatesElement;
      break;
    default:
      break;
    }
    return true;
  }

  bool StartObject() {
    switch (state_) {
    case kStart:
      state_ = kRoot;
      break;
    case kCoordinatesArray:
      state_ = kCoordinatesElement;
      break;
    default:
      break;
    }
    return true;
  }

  bool Key(const Ch *str, SizeType len, bool) {
    switch (state_) {
    case kRoot:
      if (len == sizeof("coordinates") - 1 &&
          memcmp(str, "coordinates", sizeof("coordinates") - 1) == 0)
        state_ = kCoordinates;
      break;

    case kCoordinatesElement:
      if (len == 1 && str[0] >= 'x' && str[0] <= 'z')
        state_ = static_cast<State>(kX + (str[0] - 'x'));
      break;

    default:
      break;
    }
    return true;
  }

  bool EndObject(SizeType) {
    switch (state_) {
    case kCoordinatesElement:
      state_ = kCoordinatesArray;
      break;
    default:
      break;
    }
    return true;
  }

  bool StartArray() {
    switch (state_) {
    case kCoordinates:
      state_ = kCoordinatesArray;
      break;
    default:
      break;
    }
    return true;
  }

  bool EndArray(SizeType len) {
    switch (state_) {
    case kCoordinatesArray:
      callback_(coordinate_t{x_ / len, y_ / len, z_ / len});
      state_ = kCoordinates;
      break;

    default:
      break;
    }
    return true;
  }

private:
  enum State {
    kStart,
    kRoot,
    kCoordinates,
    kCoordinatesArray,
    kCoordinatesElement,
    kX,
    kY,
    kZ
  } state_;

  double x_, y_, z_;

  TCallback callback_;
};

void read_file(const string &filename, stringstream &buffer) {
  ifstream file{filename};
  if (file.good()) {
    buffer << file.rdbuf();
  }
}

void calc(stringstream &ss, const TCallback &callback) {
  IStreamWrapper isw(ss);
  Reader reader;
  CoordinateHandler handler(callback);
#ifdef PRECISED
  reader.Parse<kParseFullPrecisionFlag>(isw, handler);
#else
  reader.Parse(isw, handler);
#endif
}

int main() {
  auto right = coordinate_t{2.0, 0.5, 0.25};
  for (auto v : {R"({"coordinates":[{"x":2.0,"y":0.5,"z":0.25}]})",
                 R"({"coordinates":[{"y":0.5,"x":2.0,"z":0.25}]})"}) {
    auto json = stringstream(v);
    calc(json, [right](const coordinate_t &left) {
      if (left != right) {
        cerr << left << " != " << right << endl;
        exit(EXIT_FAILURE);
      }
    });
  }

  stringstream ss;
  read_file("/tmp/1.json", ss);

#ifdef PRECISED
  static constexpr auto SUFFIX = " Precise";
#else
  static constexpr auto SUFFIX = "";
#endif

  coordinate_t results;
  notifying_invoke(
      [&]() { calc(ss, [&](const coordinate_t &v) { results = v; }); },
      "C++/{} (RapidJSON SAX{})", COMPILER, SUFFIX);

  cout << results << endl;
}


text:
title:       Geospatial Conservation Assessment Tool
short_title: GeoCAT
summary: 	 Finding endangered species before it's too late
description: 'An interactive geospatial tool to help researchers and NGOs to assess the conservation level of species across the globe'
fb_title:    "GeoCAT | Vizzuality"
fb_description: "A tool to assess the conservation level of species across the globe"
link:        http://geocat.kew.org
link_short:  geocat.kew.org
client:      Kew Gardens, IUCN and ViBRANT
client_logo: kew.png
svg_logo:
post_url:    http://blog.vizzuality.com/post/122340435976/opening-data-to-increase-impact
post_title:  "Opening Data to Increase Impact"
image:       red-list_02.jpg
cover:  	 red-list_02.jpg
author:      Jamie Gibson
date:        2015-05-07
release_date:  December 2013
highlighted:   true
logoWidth:  102

modules:

    -   text_left:
            title: Making it easy to assess species
            description: "We made intensive use of effects and animations to display the status of the tool, providing continuous feedback to the user as they make their assessment. And with unlimited undo and redo, all user actions can be undone and redone at any time, encouraging a trial-and-error analysis refinement."
            image: red-list_high1.jpg

    -   text_right:
        	title: Evolving all the time
        	description: "As part of the EU BON project we are adding a couple of new features, allowing users to complete even more powerful analyses using biodiversity observations from across Europe. Watch out for new features and data coming out soon!"
        	image: red-list_high2.jpg

    -   map:
            title: "Start your own assessment"
            description:
            url: http://geocat.kew.org/editor

    -   video:
            title: Introducing GeoCAT
            url: http://player.vimeo.com/video/22739331

---
The Red List of Species captures the threat level for the world's species; it helps conservation experts in governments and NGOs to target actions to protect the most vulnerable species before they disappear forever. Putting together Red List assessments can take some time though and involves tonnes of spatial data. We built GeoCAT with Kew Gardens, ViBRANT and IUCN, to make this process easier and quicker. There is so much data out there on the web, from established biodiversity databases like GBIF to more citizen-oriented databases like iNaturalist and Flickr; GeoCAT neatly allows anyone to pull in this data, or upload their own data, and create an assessment quickly and easily. Since the first release we've continued to improve the experience through the EU BON project.


text:
package com.bushstar.htmlcoinj.store;

/**
 * Thrown when something goes wrong with storing a block. Examples: out of disk space.
 */
public class BlockStoreException extends Exception {
    public BlockStoreException(String message) {
        super(message);
    }

    public BlockStoreException(Throwable t) {
        super(t);
    }
}


text:
import os
import inspect

from meshless.espim.read_mesh import read_mesh

THISDIR = os.path.dirname(inspect.getfile(inspect.currentframe()))

def test_read_mesh():
    mesh = read_mesh(os.path.join(THISDIR, 'nastran_plate_16_nodes.dat'))
    assert len(mesh.nodes) == 16
    assert len(mesh.elements) == 18
    assert len(mesh.edges) == 33


text:
layout: post
title: 038 - Bavarian Cider
description: 038 - Bavarian Cider
modified: 11/6/2013 4:42:10 PM
category: beers
tags: []
image:
  texture-feature-05.jpg
---

## Grain

| Name | Amount %|
| ---- | ------: |
| Apple Cider | 97.3
| Candi Sugar, Dark | 2.60

## Yeast
Wyeast Labs Bavarian Wheat Yeast

## Notes
4.5 gallons of Anderson orchard cider
1 pouch Extra dark candi sugar (180)
1 Pack wy3056

This batch had a pretty active fermentation and blew the air lock off of the carboy. Added in about a quart of unfermented frozen cider back at kegging time for a little sweetness. Ended up tasting probably a little bit better than the english yeast. For some reason it refuses to carb, even after close to 3 weeks on CO2 it nearly flat.


text:
"""Python filesystem abstraction layer.
"""

__import__("pkg_resources").declare_namespace(__name__)  # type: ignore

from . import path
from ._fscompat import fsdecode, fsencode
from ._version import __version__
from .enums import ResourceType, Seek
from .opener import open_fs

__all__ = ["__version__", "ResourceType", "Seek", "open_fs"]


text:
SET @iPageId = (SELECT `id` FROM `sys_std_pages` WHERE `name`='bx_froala' LIMIT 1);
UPDATE `sys_std_widgets` SET `type`='integrations' WHERE `page_id`=@iPageId;


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.iosdevlog.bookdrawerfragment">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".BookActivity"
            android:label="@string/title_activity_book">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


text:
import { bindActionCreators } from 'redux';
import Primus from 'primus';
import { camelizeKeys } from 'humps';
import { receiveMessage, receiveTyping } from 'app/actions/conversation';
import * as ActionTypes from 'app/ActionTypes';

export function createPushClient(primusUrl, store) {
  const actions = bindActionCreators({
    [ActionTypes.RECEIVE_TYPING]: receiveTyping,
    [ActionTypes.RECEIVE_MESSAGE]: receiveMessage,
  }, store.dispatch);

  const primus = Primus.connect(primusUrl, {
    reconnect: {
      retries: Infinity,
    },
  });

  primus.on('open', () => {
    primus.write({
      type: ActionTypes.REGISTER,
      payload: { user_id: store.getState().users.current.id }, // TODO: use session token instead
    });
  });

  primus.on('data', data => {
    const { type, payload } = camelizeKeys(data);
    const action = actions[type];
    if (DEBUG && !action) {
      throw Error(`unknown action type: ${type}`);
    }
    action(payload);
  });

  return {
    destroy: () => primus.destroy(),
  };
}

export default createPushClient;


text:
#import <Foundation/Foundation.h>
#if __has_include("BraintreeCore.h")
#import "BraintreeCore.h"
#else
#import <BraintreeCore/BraintreeCore.h>
#endif
#import "BTPaymentFlowResult.h"

NS_ASSUME_NONNULL_BEGIN

/**
 The result of an local payment flow
 */
@interface BTLocalPaymentResult : BTPaymentFlowResult

/**
 The billing address.
 */
@property (nonatomic, nullable, readonly, strong) BTPostalAddress *billingAddress;

/**
 Client Metadata Id associated with this transaction.
 */
@property (nonatomic, nullable, readonly, copy) NSString *clientMetadataId;

/**
 Payer's email address.
 */
@property (nonatomic, nullable, readonly, copy) NSString *email;

/**
 Payer's first name.
 */
@property (nonatomic, nullable, readonly, copy) NSString *firstName;

/**
 Payer's last name.
 */
@property (nonatomic, nullable, readonly, copy) NSString *lastName;

/**
 A localized description of the payment info.
 */
@property (nonatomic, readonly, copy) NSString *localizedDescription;

/**
 The one-time use payment method nonce.
 */
@property (nonatomic, readonly, copy) NSString *nonce;

/**
 Optional. Payer Id associated with this transaction.
 */
@property (nonatomic, nullable, readonly, copy) NSString *payerId;

/**
 Payer's phone number.
 */
@property (nonatomic, nullable, readonly, copy) NSString *phone;

/**
 The shipping address.
 */
@property (nonatomic, nullable, readonly, strong) BTPostalAddress *shippingAddress;

/**
 The type of the tokenized payment.
 */
@property (nonatomic, readonly, copy) NSString *type;

/**
 Creates a BTLocalPaymentResult.

 @param nonce The one-time use payment method nonce.
 @param description A localized description of the payment info.
 @param type The type of the tokenized payment.
 @param email Payer's email address.
 @param firstName Payer's first name.
 @param lastName Payer's last name.
 @param phone Payer's phone number.
 @param billingAddress The billing address.
 @param shippingAddress The shipping address.
 @param clientMetadataId Client Metadata Id associated with this transaction.
 @param payerId Payer Id associated with this transaction.
 */
- (instancetype)initWithNonce:(NSString *)nonce
                  description:(NSString *)description
                         type:(NSString *)type
                        email:(NSString *)email
                    firstName:(NSString *)firstName
                     lastName:(NSString *)lastName
                        phone:(NSString *)phone
               billingAddress:(BTPostalAddress *)billingAddress
              shippingAddress:(BTPostalAddress *)shippingAddress
             clientMetadataId:(NSString *)clientMetadataId
                      payerId:(NSString *)payerId;

@end

NS_ASSUME_NONNULL_END


text:
<?php

/**
 * Spanish language for the Config Manager
 *
 * If your language is not/only partially translated or you found an error/typo,
 * have a look at the following files:
 * - "/lib/tpl/mnml-blog/lang/<your lang>/lang.php"
 * - "/lib/tpl/mnml-blog/lang/<your lang>/settings.php"
 * If they are not existing, copy and translate the English ones. And don't
 * forget to mail the translation to us,
 * SYN Systems <dokuwiki@dev.syn-systems.com>. Thanks :-D.
 *
 *
 * LICENSE: This file is open source software (OSS) and may be copied under
 *          certain conditions. See COPYING file for details or try to contact
 *          the author(s) of this file in doubt.
 *
 * @license GPLv2 (http://www.gnu.org/licenses/gpl2.html)
 * @author Adrián Rodríguez Vargas <info@adrianrodriguez.es>
 * @link http://www.dokuwiki.org/template:mnml-blog
 * @link http://www.dokuwiki.org/config:lang
 * @link http://www.dokuwiki.org/devel:configuration
 */

//check if we are running within the DokuWiki environment
if (!defined("DOKU_INC")){
    die();
}

//header navigation
$lang["mnmlblog_headernav"]          = "¿Mostrar categorías de navegación?";
$lang["mnmlblog_headernav_location"] = "En caso afirmativo, usar la siguiente wiki como principal:";

//sidebar navigation
$lang["mnmlblog_sidebarnav"]          = "¿Mostrar barra de navegación?";
$lang["mnmlblog_sidebarnav_location"] = "En caso afirmativo, usar la siguiente página como barra de navegación:";

//custom copyright notice
$lang["mnmlblog_copyright"]          = "¿Mostrar copyright?";
$lang["mnmlblog_copyright_default"]  = "En caso afirmativo, ¿usar el copyright por defecto?";
$lang["mnmlblog_copyright_location"] = "Si no hay por defecto, usar la siguiente página como licencia de copyright:";

//search form
$lang["mnmlblog_search"]    = "¿Mostrar formulario de búsqueda?";
$lang["mnmlblog_search_pos"] = "En caso afirmativo, ¿En que posición quieres mostrarl?";

//other stuff
$lang["mnmlblog_newpostform_location"] = "Usar la siguiente página para el formulario '<blog newform>'";
$lang["mnmlblog_loaduserjs"]           = "¿Cargar 'mnml-blog/user/user.js'?";


text:
/**
 * WEB ANGULAR VERSION
 * (based on systemjs.config.js in angular.io)
 * System configuration for Angular samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
  System.config({
    // DEMO ONLY! REAL CODE SHOULD NOT TRANSPILE IN THE BROWSER
    transpiler: 'ts',
    typescriptOptions: {
      // Copy of compiler options in standard tsconfig.json
      "target": "es5",
      // "outDir": "./dist/out-tsc",
      "baseUrl": "src",
      "sourceMap": true,
      "declaration": false,
      "moduleResolution": "node",
      "emitDecoratorMetadata": true,
      "experimentalDecorators": true,
      // "module": "commonjs",
      // "moduleResolution": "node",
      // "sourceMap": true,
      // "emitDecoratorMetadata": true,
      // "experimentalDecorators": true,
      "lib": ["es2016", "dom"],
      // "noImplicitAny": true,
      "typeRoots": [
        "node_modules/@types"
      ],
      // "suppressImplicitAnyIndexErrors": true
    },
    meta: {
      'typescript': {
        "exports": "ts"
      }
    },
    paths: {
      // paths serve as alias
      // "*": "*.ts", // should load all libraries with .ts appended
      'npm:': 'https://unpkg.com/'
    },
    // map tells the System loader where to look for things
    map: {
      // our app is within the app folder
      'environments/environment': 'http://localhost:8000/websites/patterns/taxonomy-lookup/tax/src/environments/environment.ts',
      'app': 'app',

      // angular bundles
      '@angular/animations': 'npm:@angular/animations/bundles/animations.umd.js',
      '@angular/animations/browser': 'npm:@angular/animations/bundles/animations-browser.umd.js',
      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
      // '@angular/platform-browser/animations': 'npm:@angular/platform-browser/bundles/platform-browser-animations.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
      // '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
      // '@angular/router/upgrade': 'npm:@angular/router/bundles/router-upgrade.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
      // '@angular/upgrade': 'npm:@angular/upgrade/bundles/upgrade.umd.js',
      // '@angular/upgrade/static': 'npm:@angular/upgrade/bundles/upgrade-static.umd.js',

      // other libraries
      'rxjs':                      'npm:rxjs@5.0.1',
      // 'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js',
      'ts':                        'npm:plugin-typescript@5.2.7/lib/plugin.js',
      'typescript':                'npm:typescript@2.2.1/lib/typescript.js',
      'ngx-bootstrap':             'npm:ngx-bootstrap/bundles/ngx-bootstrap.umd.js'

    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      app: {
        transpiler: 'ts',
        main: './main.ts',
        defaultExtension: 'ts',
        meta: {
          // './*.ts': {
          //   loader: 'systemjs-angular-loader.js'
          // }
        }
      },
      rxjs: {
        defaultExtension: 'js'
      }
    }
  });

})(this);


text:
from django.conf.urls import url, include
from eulcommon.djangoextras.taskresult import urls as taskresult_urls

urlpatterns = [
    url(r'^tasks/', include(taskresult_urls, namespace='tasks')),
]


text:
package io.advantageous.qbit.http;

import io.advantageous.boon.core.Sys;
import io.advantageous.qbit.Factory;
import io.advantageous.qbit.http.config.HttpServerOptions;
import io.advantageous.qbit.http.request.HttpRequest;
import io.advantageous.qbit.http.request.HttpResponseCreator;
import io.advantageous.qbit.http.request.decorator.HttpResponseDecorator;
import io.advantageous.qbit.http.server.HttpServer;
import io.advantageous.qbit.http.server.HttpServerBuilder;
import io.advantageous.qbit.http.server.RequestContinuePredicate;
import io.advantageous.qbit.http.server.impl.SimpleHttpServer;
import io.advantageous.qbit.http.server.websocket.WebSocketMessage;
import io.advantageous.qbit.service.discovery.ServiceDiscovery;
import io.advantageous.qbit.service.health.HealthServiceAsync;
import io.advantageous.qbit.spi.FactorySPI;
import io.advantageous.qbit.system.QBitSystemManager;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

import static io.advantageous.boon.core.Exceptions.die;

public class HttpServerBuilderTest {

    HttpServerBuilder objectUnderTest;

    Consumer<WebSocketMessage> webSocketMessageConsumer;
    Consumer<HttpRequest> httpRequestConsumer;
    boolean ok;

    @Before
    public void setUp() throws Exception {

        objectUnderTest = new HttpServerBuilder();

        webSocketMessageConsumer = webSocketMessage -> {

        };

        httpRequestConsumer = request -> {

        };

        FactorySPI.setFactory(new Factory() {

            public HttpServer createHttpServer(HttpServerOptions options,
                                               String endpointName,
                                               QBitSystemManager systemManager,
                                               ServiceDiscovery serviceDiscovery,
                                               HealthServiceAsync healthServiceAsync,
                                               final int serviceDiscoveryTtl,
                                               final TimeUnit serviceDiscoveryTtlTimeUnit,
                                               final CopyOnWriteArrayList<HttpResponseDecorator> decorators,
                                               final HttpResponseCreator httpResponseCreator, RequestContinuePredicate requestBodyContinuePredicate) {

                return FactorySPI.getHttpServerFactory().create(options, endpointName, systemManager, serviceDiscovery,
                        healthServiceAsync, serviceDiscoveryTtl, serviceDiscoveryTtlTimeUnit, decorators, httpResponseCreator, requestBodyContinuePredicate);
            }
        });

        FactorySPI.setHttpServerFactory((options, name, systemManager, serviceDiscovery, healthServiceAsync, a, b, c, d, z)
                -> new SimpleHttpServer());
        Sys.sleep(100);

    }

    @After
    public void tearDown() {
        FactorySPI.setFactory(null);

    }

    @Test
    public void test() throws Exception {

        ok = objectUnderTest.setHost("host").getHost().equals("host") || die();
        ok = objectUnderTest.setHost("localhost").getHost().equals("localhost") || die();

        ok = objectUnderTest.setPipeline(true).isPipeline() || die();
        ok = !objectUnderTest.setPipeline(false).isPipeline() || die();

        ok = objectUnderTest.setPort(9090).getPort() == 9090 || die();
        ok = objectUnderTest.setPort(8080).getPort() == 8080 || die();

        ok = objectUnderTest.setFlushInterval(909).getFlushInterval() == 909 || die();
        ok = objectUnderTest.setFlushInterval(808).getFlushInterval() == 808 || die();

        objectUnderTest.build();

    }
}


text:
var http = require('http');
var fs = require('fs');
var path = require('path');
var alloc = require('tcp-bind');
var xtend = require('xtend');

var settings = require('../settings.js');

var minimist = require('minimist');
var argv = minimist(process.argv.slice(2), {
    alias: {
        d: 'datadir', p: 'port', u: 'uid', g: 'gid',
        h: 'help', D: 'debug'
    },
    default: {
        datadir: 'sudoroom-data',
        port: require('is-root')() ? 80 : 8000
    }
});
if (argv.help || argv._[0] === 'help') {
    fs.createReadStream(__dirname + '/usage.txt').pipe(process.stdout);
    return;
}

var fd = alloc(argv.port);
if (argv.gid) process.setgid(argv.gid);
if (argv.uid) process.setgid(argv.uid);

var hyperstream = require('hyperstream');
var ecstatic = require('ecstatic')({
    root: __dirname + '/../static',
    gzip: true
});
var mkdirp = require('mkdirp');

var level = require('level');
var sublevel = require('subleveldown');
var bytewise = require('bytewise');

var dir = {
    data: path.join(argv.datadir, 'data'),
    index: path.join(argv.datadir, 'index'),
    session: path.join(argv.datadir, 'session'),
    blob: path.join(argv.datadir, 'blob')
};
mkdirp.sync(dir.blob);

var ixfeed = require('index-feed');
var ixdb = level(dir.index);
var counts = require('../lib/counts.js')(
    sublevel(ixdb, 'c', { valueEncoding: 'json' })
);
var ixf = ixfeed({
    data: level(dir.data),
    index: sublevel(ixdb, 'i'),
    valueEncoding: 'json'
});

ixf.index.add(function (row, cb) {
    if (row.value && row.value.type === 'user') {

        var ix = {
            'user.id': row.value.id,
            'user.name': row.value.name,
            'user.email': row.value.email,
            'user.visibility': row.value.visibility
        };

        var isMember = false;
        var collective, isCollectiveMember, isCollectiveUser;
        var c = {};
        for(collective in settings.collectives) {
            isCollectiveMember = false;
            isCollectiveUser = false;
            ix['user.'+collective] = false;
            ix['member.'+collective] = false;
            if(row.value.collectives && row.value.collectives[collective]) {
                ix['user.'+collective] = true;
                isCollectiveUser = true;
                if(row.value.collectives[collective].privs.indexOf('member') >= 0) {
                    ix['member.'+collective] = true;
                    isMember = true;
                    isCollectiveMember = true;
                }
            }

            if (!row.prev) {
                c['user.'+collective] = isCollectiveUser ? 1 : 0;
                c['member.'+collective] = isCollectiveMember ? 1 : 0;
            } else {
                if(isCollectiveUser !== row.prev['user.'+collective]) {

                    c['user.'+collective] = isCollectiveUser ? 1 : -1;;
                }
                if(isCollectiveMember !== row.prev['member.'+collective]) {
                    c['member.'+collective] = isCollectiveMember ? 1 : -1;
                }
            }

        }

        ix['user.member'] = isMember;

        if (!row.prev) {
            c['user'] = 1;
            c['member'] = isMember ? 1 : 0;

        }
        else if (isMember !== row.prev['user.member']) {
            c['member'] = isMember ? 1 : -1;
        }

        if(Object.keys(c).length > 0) {
            counts.add(c, done);
        } else {
            done()
        }

        function done (err) { cb(err, ix) }
    }
    else cb()
});

var accountdown = require('accountdown');
var users = accountdown(sublevel(ixf.db, 'users'), {
    login: { basic: require('accountdown-basic') }
});

var auth = require('cookie-auth')({
    name: require('../package.json').name,
    sessions: level(dir.session)
});

var store = require('content-addressable-blob-store');
var blob = store({ path: dir.blob });

var layout = require('../lib/layout.js')(auth);

var router = require('routes')();
router.addRoute('/', layout('main.html',
    require('../routes/main.js')(ixf, counts, settings)
));
router.addRoute('/c/:collective', layout('collective.html',
    require('../routes/collective.js')(ixf, counts, settings)
));
router.addRoute('/account/create', layout('create_account.html'));
router.addRoute('/account/create/post',
    require('../routes/create_account.js')(users, auth, blob, argv, settings)
);
router.addRoute('/account/sign-in', layout('sign_in.html'));
router.addRoute('/account/sign-in/post',
    require('../routes/sign_in.js')(users, auth)
);

router.addRoute('/account/password-reset', layout('password_reset.html'));
router.addRoute('/account/password-reset-success', layout('password_reset_success.html'));
router.addRoute('/account/password-reset/post',
    require('../routes/password_reset.js')(users, ixf.index, argv)
);

router.addRoute('/account/sign-out/:token',
    require('../routes/sign_out.js')(auth)
);
router.addRoute('/~:name/welcome',
                require('../routes/welcome.js')(auth, ixf, blob)
);
router.addRoute('/~:name.:ext', require('../routes/ext.js')(ixf, blob));
router.addRoute('/~:name', require('../routes/profile.js')(auth, ixf, blob, settings));
router.addRoute('/~:name/edit',
    require('../routes/edit_profile.js')(users, auth, blob, settings)
);
router.addRoute('/~:name/:collective/membership',
    require('../routes/payment.js')(users, auth, blob, settings)
);

router.addRoute('/c/:collective/members',
    require('../routes/members.js')(users, auth, blob, settings)
);

router.addRoute('/c/:collective/email/users',
    require('../routes/email_list.js')('users', ixf.index, users, settings)
);
router.addRoute('/c/:collective/email/members',
    require('../routes/email_list.js')('members', ixf.index, users, settings)
);

router.addRoute('/admin/dump',
    require('../routes/dump.js')(ixf.index, users)
);

var server = http.createServer(function (req, res) {
    var m = router.match(req.url);
    if (!m) return ecstatic(req, res);
    var rparams = {
        params: m.params,
        error: error
    };
    auth.handle(req, res, function (err, session) {
        rparams.session = session && xtend(session, { update: update });
        m.fn(req, res, rparams);

        function update (v, cb) {
            var data = xtend(session, { data: xtend(session.data, v) });

            auth.sessions.put(session.session, data, { valueEncoding: 'json' },
            function (err) {
                if (err) cb && cb(err)
                else cb && cb(null)
            });
        }
    });

    function error (code, err) {
        res.statusCode = code;
        layout('error.html', function () {
            return hyperstream({ '.error': { _text: err + '\n' } });
        })(req, res, rparams);
    }
});
server.listen({ fd: fd }, function () {
    if(argv.debug) {
        // debug mode will print plaintext passwords to stdout
        // during account creation and password reset
        // it will however not leak credit card information
        // since that is never sent to the server (it is only sent to stripe)
        console.log('WARNING: Debug mode enabled. Will leak private user data to stdout (though not credit card info).');
    }
    console.log('listening on :' + server.address().port);
});