text:
package org.rapidpm.vaadin.testbench.addon;

import static org.rapidpm.frp.memoizer.Memoizer.memoize;
import static org.rapidpm.frp.vaadin.addon.testbench.BrowserDriverFunctions.ipSupplierLocalIP;
import static org.rapidpm.microservice.MainUndertow.MYAPP;
import static org.rapidpm.microservice.MainUndertow.SERVLET_PORT_PROPERTY;

import java.io.File;
import java.util.function.Supplier;

import org.rapidpm.dependencies.core.net.PortUtils;
import org.rapidpm.microservice.MainUndertow;

/**
 * Created by svenruppert on 23.04.17.
 */
public class MicroserviceTestUtils {

  private MicroserviceTestUtils() {
  }

  public static void initSystemProperties() {
    final String pointToStartFrom = new File("").getAbsolutePath();
    final String dataDriverBaseFolder = "/_data/driver/";
    final String os = "osx";

    String basePath = pointToStartFrom + dataDriverBaseFolder + os;
    System.setProperty("webdriver.chrome.driver" , basePath + "/chrome/chromedriver");
    System.setProperty("webdriver.gecko.driver" , basePath + "/gecko/geckodriver");
    System.setProperty("phantomjs.binary.path" , basePath + "/phantomjs/phantomjs");

    System.setProperty("org.rapidpm.microservice.security.shiro.active" , "false");
  }

  public static void setUpMicroserviceProperties() {
    final PortUtils portUtils = new PortUtils();

    System.setProperty(MainUndertow.REST_HOST_PROPERTY , ipSupplierLocalIP.get());
    System.setProperty(MainUndertow.SERVLET_HOST_PROPERTY , ipSupplierLocalIP.get());

    System.setProperty(MainUndertow.REST_PORT_PROPERTY , portUtils.nextFreePortForTest() + "");
    System.setProperty(MainUndertow.SERVLET_PORT_PROPERTY , portUtils.nextFreePortForTest() + "");
  }

  public static Supplier<String> memoizedLocalIpSupplier = memoize(ipSupplierLocalIP);

  public static Supplier<String> baseURL =
      () -> "http://"
            + memoizedLocalIpSupplier.get() + ":"
//             + memoizedServletPortSupplier.get() + "/"
            + System.getProperty(SERVLET_PORT_PROPERTY) + "/"
            + MYAPP;

}


text:
package renter

import (
	"encoding/json"
	"io/ioutil"
	"os"
	"path/filepath"
	"testing"

	"github.com/NebulousLabs/Sia/build"
	"github.com/NebulousLabs/Sia/crypto"
)

// TestRenterSaveAndLoad probes the save and load methods of the renter type.
func TestRenterSaveAndLoad(t *testing.T) {
	rt := newRenterTester("TestRenterSaveAndLoad", t)

	rt.renter.files["1"] = &file{
		Name:     "1",
		Checksum: crypto.HashObject("fake id"),

		Pieces: []filePiece{
			filePiece{
				Active:    true,
				Repairing: true,
			},
			filePiece{
				Active:    true,
				Repairing: false,
			},
		},

		renter: rt.renter,
	}
	rt.renter.files["2"] = &file{
		Name: "2",
		Pieces: []filePiece{
			filePiece{
				Active:    false,
				Repairing: true,
			},
			filePiece{
				Active:    false,
				Repairing: false,
			},
		},
	}
	lockID := rt.renter.mu.Lock()
	rt.renter.save()
	rt.renter.mu.Unlock(lockID)

	// Create a new renter that calls load.
	r, err := New(rt.cs, rt.hostdb, rt.wallet, rt.renter.saveDir)
	if err != nil {
		t.Fatal(err)
	}
	lockID = rt.renter.mu.Lock()
	err = r.load()
	rt.renter.mu.Unlock(lockID)
	if err != nil {
		t.Fatal(err)
	}

	if r.files["1"].Name != "1" {
		t.Error("Name didn't load correctly")
	}
	if r.files["1"].Checksum != crypto.HashObject("fake id") {
		t.Error("Checksum didn't load correctly")
	}
	if r.files["1"].Pieces[0].Active != true {
		t.Error("Pieces.Active didn't load correctly")
	}
	if r.files["1"].Pieces[0].Repairing != true {
		t.Error("Pieces.Repairing didn't load correctly")
	}
	if r.files["1"].Pieces[1].Active != true {
		t.Error("Pieces.Active didn't load correctly")
	}
	if r.files["1"].Pieces[1].Repairing != false {
		t.Error("Pieces.Repairing didn't load correctly")
	}
	if r.files["2"].Name != "2" {
		t.Error("Name didn't load correctly")
	}
	if r.files["2"].Pieces[0].Active != false {
		t.Error("Pieces.Active didn't load correctly")
	}
	if r.files["2"].Pieces[0].Repairing != true {
		t.Error("Pieces.Repairing didn't load correctly")
	}
	if r.files["2"].Pieces[1].Active != false {
		t.Error("Pieces.Active didn't load correctly")
	}
	if r.files["2"].Pieces[1].Repairing != false {
		t.Error("Pieces.Repairing didn't load correctly")
	}

	// Check that the mutex for the files was set correctly.
	_ = r.files["1"].Nickname() // will panic if mutex is wrong.

	// Read the file into the persist structure and try various forms of
	// corruption.
	persistFile := filepath.Join(r.saveDir, PersistFilename)
	persistBytes, err := ioutil.ReadFile(persistFile)
	if err != nil {
		t.Fatal(err)
	}
	var rp RenterPersistence
	err = json.Unmarshal(persistBytes, &rp)
	if err != nil {
		t.Fatal(err)
	}

	// Change the header.
	rp.Header = "bad"
	badBytes, err := json.Marshal(rp)
	if err != nil {
		t.Fatal(err)
	}
	err = ioutil.WriteFile(persistFile, badBytes, 0660)
	if err != nil {
		t.Fatal(err)
	}
	lockID = rt.renter.mu.Lock()
	err = r.load()
	rt.renter.mu.Unlock(lockID)
	if err != ErrUnrecognizedHeader {
		t.Error("Expecting ErrUnrecognizedHeader:", err)
	}

	// Change the version.
	rp.Header = PersistHeader
	rp.Version = "bad"
	badBytes, err = json.Marshal(rp)
	if err != nil {
		t.Fatal(err)
	}
	err = ioutil.WriteFile(persistFile, badBytes, 0660)
	if err != nil {
		t.Fatal(err)
	}
	lockID = rt.renter.mu.Lock()
	err = r.load()
	rt.renter.mu.Unlock(lockID)
	if err != ErrUnrecognizedVersion {
		t.Error("Expecting ErrUnrecognizedVersion:", err)
	}

	// Corrupt the file
	err = ioutil.WriteFile(persistFile, badBytes[1:], 0660)
	if err != nil {
		t.Fatal(err)
	}
	lockID = rt.renter.mu.Lock()
	err = r.load()
	rt.renter.mu.Unlock(lockID)
	if err == nil {
		t.Error("failed to corrupt the file")
	}
}

// TestFileSharing probes the LoadSharedFile and the ShareFile methods of the
// renter.
func TestFileSharing(t *testing.T) {
	// Create a directory to put all the files shared between the renters in
	// this test.
	t.Skip("broken")
	shareDir := build.TempDir("renter", "TestFileSharing")
	err := os.MkdirAll(shareDir, 0700)
	if err != nil {
		t.Fatal(err)
	}

	rt1 := newRenterTester("TestFileSharing - 1", t)
	rt2 := newRenterTester("TestFileSharing - 2", t)

	// Try to share a file from an empty renter.
	err = rt1.renter.ShareFiles([]string{"dne"}, filepath.Join(shareDir, "badshare.sia"))
	if err != ErrUnknownNickname {
		t.Error("Expecting ErrUnknownNickname:", err)
	}

	// Add a file to rt1 and share it with rt2.
	rt1.renter.files["1"] = &file{
		Name:     "1",
		Checksum: crypto.HashObject("fake id"),

		Pieces: []filePiece{
			filePiece{
				Active:    true,
				Repairing: true,
			},
			filePiece{
				Active:    true,
				Repairing: false,
			},
		},

		renter: rt1.renter,
	}
	err = rt1.renter.ShareFiles([]string{"1"}, filepath.Join(shareDir, "1share.sia"))
	if err != nil {
		t.Fatal(err)
	}
	_, err = rt2.renter.LoadSharedFile(filepath.Join(shareDir, "1share.sia"))
	if err != nil {
		t.Fatal(err)
	}
	if len(rt2.renter.files) != 1 {
		t.Error("rt2 did not load the shared file")
	}

	// Try sharing nothing, and using an incorrect suffix.
	err = rt1.renter.ShareFiles([]string{}, filepath.Join(shareDir, "2share.sia"))
	if err != ErrNoNicknames {
		t.Error("Expecting ErrNoNicknames")
	}
	err = rt1.renter.ShareFiles([]string{"1"}, filepath.Join(shareDir, "3share.sia1"))
	if err != ErrNonShareSuffix {
		t.Error("Expecting ErrNonShareSuffix", err)
	}

	// Load a non-existant file.
	_, err = rt1.renter.LoadSharedFile(filepath.Join(shareDir, "0share.sia"))
	if err == nil {
		t.Error("expected error")
	}

	// Create and load a corrupt file.
	shareBytes, err := ioutil.ReadFile(filepath.Join(shareDir, "1share.sia"))
	if err != nil {
		t.Fatal(err)
	}
	err = ioutil.WriteFile(filepath.Join(shareDir, "1share.sia"), shareBytes[1:], 0660)
	if err != nil {
		t.Fatal(err)
	}
	_, err = rt1.renter.LoadSharedFile(filepath.Join(shareDir, "1share.sia"))
	if err == nil {
		t.Error("Expecting corruption error")
	}
}

redpajama_set_name: RedPajamaGithub


text:
"""
test_openstack_catalog
----------------------------------

Tests for `openstack_catalog` module.
"""

from openstack_catalog.tests import base

class TestOpenstack_catalog(base.TestCase):

    def test_something(self):
        pass


text:
package org.wso2.carbon.apimgt.impl.notifier.events;

import java.util.Objects;

/**
 * An Event Object which can holds the data related to Application which are required
 * for the validation purpose in a gateway.
 */
public class ApplicationEvent extends Event {
    private int applicationId;
    private String applicationName;
    private String tokenType;
    private String applicationPolicy;
    private String groupId;

    public ApplicationEvent(String eventId, long timestamp, String type, int tenantId,int applicationId,
                            String applicationName, String tokenType, String applicationPolicy, String groupId) {
        this.eventId = eventId;
        this.timeStamp = timestamp;
        this.type = type;
        this.tenantId = tenantId;
        this.applicationId = applicationId;
        this.applicationName = applicationName;
        this.tokenType = tokenType;
        this.applicationPolicy = applicationPolicy;
        this.groupId = groupId;
    }

    @Override
    public String toString() {
        return "ApplicationEvent{" +
                "applicationId=" + applicationId +
                ", applicationName='" + applicationName + '\'' +
                ", tokenType='" + tokenType + '\'' +
                ", applicationPolicy='" + applicationPolicy + '\'' +
                ", groupId='" + groupId + '\'' +
                ", eventId='" + eventId + '\'' +
                ", timeStamp=" + timeStamp +
                ", type='" + type + '\'' +
                ", tenantId=" + tenantId +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof ApplicationEvent)) return false;
        ApplicationEvent that = (ApplicationEvent) o;
        return getApplicationId() == that.getApplicationId() &&
                getApplicationName().equals(that.getApplicationName()) &&
                getTokenType().equals(that.getTokenType()) &&
                getGroupId().equals(that.getGroupId()) &&
                getApplicationPolicy().equals(that.getApplicationPolicy());
    }

    @Override
    public int hashCode() {
        return Objects.hash(getApplicationId(), getApplicationName(), getTokenType(), getApplicationPolicy(), getGroupId());
    }

    public int getApplicationId() {
        return applicationId;
    }

    public void setApplicationId(int applicationId) {
        this.applicationId = applicationId;
    }

    public String getApplicationName() {
        return applicationName;
    }

    public void setApplicationName(String applicationName) {
        this.applicationName = applicationName;
    }

    public String getTokenType() {
        return tokenType;
    }

    public void setTokenType(String tokenType) {
        this.tokenType = tokenType;
    }

    public String getApplicationPolicy() {
        return applicationPolicy;
    }

    public void setApplicationPolicy(String applicationPolicy) {
        this.applicationPolicy = applicationPolicy;
    }

    public String getGroupId() {
        return groupId;
    }

    public void setGroupId(String groupId) {
        this.groupId = groupId;
    }
}


text:
package org.apache.lucene.index;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.MockAnalyzer;
import org.apache.lucene.document.BinaryDocValuesField;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.SortedDocValuesField;
import org.apache.lucene.document.SortedSetDocValuesField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.search.FieldCache;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util.LuceneTestCase.SuppressCodecs;

/**
 *
 * Tests DocValues integration into IndexWriter
 *
 */
@SuppressCodecs("Lucene3x")
public class TestDocValuesIndexing extends LuceneTestCase {
  /*
   * - add test for multi segment case with deletes
   * - add multithreaded tests / integrate into stress indexing?
   */

  public void testAddIndexes() throws IOException {
    Directory d1 = newDirectory();
    RandomIndexWriter w = new RandomIndexWriter(random(), d1);
    Document doc = new Document();
    doc.add(newStringField("id", "1", Field.Store.YES));
    doc.add(new NumericDocValuesField("dv", 1));
    w.addDocument(doc);
    IndexReader r1 = w.getReader();
    w.close();

    Directory d2 = newDirectory();
    w = new RandomIndexWriter(random(), d2);
    doc = new Document();
    doc.add(newStringField("id", "2", Field.Store.YES));
    doc.add(new NumericDocValuesField("dv", 2));
    w.addDocument(doc);
    IndexReader r2 = w.getReader();
    w.close();

    Directory d3 = newDirectory();
    w = new RandomIndexWriter(random(), d3);
    w.addIndexes(SlowCompositeReaderWrapper.wrap(r1), SlowCompositeReaderWrapper.wrap(r2));
    r1.close();
    d1.close();
    r2.close();
    d2.close();

    w.forceMerge(1);
    DirectoryReader r3 = w.getReader();
    w.close();
    AtomicReader sr = getOnlySegmentReader(r3);
    assertEquals(2, sr.numDocs());
    NumericDocValues docValues = sr.getNumericDocValues("dv");
    assertNotNull(docValues);
    r3.close();
    d3.close();
  }

  public void testMultiValuedDocValuesField() throws Exception {
    Directory d = newDirectory();
    RandomIndexWriter w = new RandomIndexWriter(random(), d);
    Document doc = new Document();
    Field f = new NumericDocValuesField("field", 17);
    // Index doc values are single-valued so we should not
    // be able to add same field more than once:
    doc.add(f);
    doc.add(f);
    try {
      w.addDocument(doc);
      fail("didn't hit expected exception");
    } catch (IllegalArgumentException iae) {
      // expected
    }

    doc = new Document();
    doc.add(f);
    w.addDocument(doc);
    w.forceMerge(1);
    DirectoryReader r = w.getReader();
    w.close();
    assertEquals(17, FieldCache.DEFAULT.getInts(getOnlySegmentReader(r), "field", false).get(0));
    r.close();
    d.close();
  }

  public void testDifferentTypedDocValuesField() throws Exception {
    Directory d = newDirectory();
    RandomIndexWriter w = new RandomIndexWriter(random(), d);
    Document doc = new Document();
    // Index doc values are single-valued so we should not
    // be able to add same field more than once:
    Field f;
    doc.add(f = new NumericDocValuesField("field", 17));
    doc.add(new BinaryDocValuesField("field", new BytesRef("blah")));
    try {
      w.addDocument(doc);
      fail("didn't hit expected exception");
    } catch (IllegalArgumentException iae) {
      // expected
    }

    doc = new Document();
    doc.add(f);
    w.addDocument(doc);
    w.forceMerge(1);
    DirectoryReader r = w.getReader();
    w.close();
    assertEquals(17, FieldCache.DEFAULT.getInts(getOnlySegmentReader(r), "field", false).get(0));
    r.close();
    d.close();
  }

  public void testDifferentTypedDocValuesField2() throws Exception {
    Directory d = newDirectory();
    RandomIndexWriter w = new RandomIndexWriter(random(), d);
    Document doc = new Document();
    // Index doc values are single-valued so we should not
    // be able to add same field more than once:
    Field f = new NumericDocValuesField("field", 17);
    doc.add(f);
    doc.add(new SortedDocValuesField("field", new BytesRef("hello")));
    try {
      w.addDocument(doc);
      fail("didn't hit expected exception");
    } catch (IllegalArgumentException iae) {
      // expected
    }
    doc = new Document();
    doc.add(f);
    w.addDocument(doc);
    w.forceMerge(1);
    DirectoryReader r = w.getReader();
    assertEquals(17, getOnlySegmentReader(r).getNumericDocValues("field").get(0));
    r.close();
    w.close();
    d.close();
  }

  // LUCENE-3870
  public void testLengthPrefixAcrossTwoPages() throws Exception {
    Directory d = newDirectory();
    IndexWriter w = new IndexWriter(d, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())));
    Document doc = new Document();
    byte[] bytes = new byte[32764];
    BytesRef b = new BytesRef();
    b.bytes = bytes;
    b.length = bytes.length;
    doc.add(new SortedDocValuesField("field", b));
    w.addDocument(doc);
    bytes[0] = 1;
    w.addDocument(doc);
    w.forceMerge(1);
    DirectoryReader r = w.getReader();
    BinaryDocValues s = FieldCache.DEFAULT.getTerms(getOnlySegmentReader(r), "field", false);

    BytesRef bytes1 = new BytesRef();
    s.get(0, bytes1);
    assertEquals(bytes.length, bytes1.length);
    bytes[0] = 0;
    assertEquals(b, bytes1);

    s.get(1, bytes1);
    assertEquals(bytes.length, bytes1.length);
    bytes[0] = 1;
    assertEquals(b, bytes1);
    r.close();
    w.close();
    d.close();
  }

  public void testDocValuesUnstored() throws IOException {
    Directory dir = newDirectory();
    IndexWriterConfig iwconfig = newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random()));
    iwconfig.setMergePolicy(newLogMergePolicy());
    IndexWriter writer = new IndexWriter(dir, iwconfig);
    for (int i = 0; i < 50; i++) {
      Document doc = new Document();
      doc.add(new NumericDocValuesField("dv", i));
      doc.add(new TextField("docId", "" + i, Field.Store.YES));
      writer.addDocument(doc);
    }
    DirectoryReader r = writer.getReader();
    AtomicReader slow = SlowCompositeReaderWrapper.wrap(r);
    FieldInfos fi = slow.getFieldInfos();
    FieldInfo dvInfo = fi.fieldInfo("dv");
    assertTrue(dvInfo.hasDocValues());
    NumericDocValues dv = slow.getNumericDocValues("dv");
    for (int i = 0; i < 50; i++) {
      assertEquals(i, dv.get(i));
      Document d = slow.document(i);
      // cannot use d.get("dv") due to another bug!
      assertNull(d.getField("dv"));
      assertEquals(Integer.toString(i), d.get("docId"));
    }
    slow.close();
    writer.close();
    dir.close();
  }

  // Same field in one document as different types:
  public void testMixedTypesSameDocument() throws Exception {
    Directory dir = newDirectory();
    IndexWriter w = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())));
    Document doc = new Document();
    doc.add(new NumericDocValuesField("foo", 0));
    doc.add(new SortedDocValuesField("foo", new BytesRef("hello")));
    try {
      w.addDocument(doc);
    } catch (IllegalArgumentException iae) {
      // expected
    }
    w.close();
    dir.close();
  }

  // Two documents with same field as different types:
  public void testMixedTypesDifferentDocuments() throws Exception {
    Directory dir = newDirectory();
    IndexWriter w = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())));
    Document doc = new Document();
    doc.add(new NumericDocValuesField("foo", 0));
    w.addDocument(doc);

    doc = new Document();
    doc.add(new SortedDocValuesField("foo", new BytesRef("hello")));
    try {
      w.addDocument(doc);
    } catch (IllegalArgumentException iae) {
      // expected
    }
    w.close();
    dir.close();
  }

  public void testAddSortedTwice() throws IOException {
    Analyzer analyzer = new MockAnalyzer(random());

    Directory directory = newDirectory();
    // we don't use RandomIndexWriter because it might add more docvalues than we expect !!!!1
    IndexWriterConfig iwc = newIndexWriterConfig(TEST_VERSION_CURRENT, analyzer);
    iwc.setMergePolicy(newLogMergePolicy());
    IndexWriter iwriter = new IndexWriter(directory, iwc);
    Document doc = new Document();
    doc.add(new SortedDocValuesField("dv", new BytesRef("foo!")));
    doc.add(new SortedDocValuesField("dv", new BytesRef("bar!")));
    try {
      iwriter.addDocument(doc);
      fail("didn't hit expected exception");
    } catch (IllegalArgumentException expected) {
      // expected
    }

    iwriter.close();
    directory.close();
  }

  public void testAddBinaryTwice() throws IOException {
    Analyzer analyzer = new MockAnalyzer(random());

    Directory directory = newDirectory();
    // we don't use RandomIndexWriter because it might add more docvalues than we expect !!!!1
    IndexWriterConfig iwc = newIndexWriterConfig(TEST_VERSION_CURRENT, analyzer);
    iwc.setMergePolicy(newLogMergePolicy());
    IndexWriter iwriter = new IndexWriter(directory, iwc);
    Document doc = new Document();
    doc.add(new BinaryDocValuesField("dv", new BytesRef("foo!")));
    doc.add(new BinaryDocValuesField("dv", new BytesRef("bar!")));
    try {
      iwriter.addDocument(doc);
      fail("didn't hit expected exception");
    } catch (IllegalArgumentException expected) {
      // expected
    }

    iwriter.close();
    directory.close();
  }

  public void testAddNumericTwice() throws IOException {
    Analyzer analyzer = new MockAnalyzer(random());

    Directory directory = newDirectory();
    // we don't use RandomIndexWriter because it might add more docvalues than we expect !!!!1
    IndexWriterConfig iwc = newIndexWriterConfig(TEST_VERSION_CURRENT, analyzer);
    iwc.setMergePolicy(newLogMergePolicy());
    IndexWriter iwriter = new IndexWriter(directory, iwc);
    Document doc = new Document();
    doc.add(new NumericDocValuesField("dv", 1));
    doc.add(new NumericDocValuesField("dv", 2));
    try {
      iwriter.addDocument(doc);
      fail("didn't hit expected exception");
    } catch (IllegalArgumentException expected) {
      // expected
    }

    iwriter.close();
    directory.close();
  }

  public void testTooLargeSortedBytes() throws IOException {
    Analyzer analyzer = new MockAnalyzer(random());

    Directory directory = newDirectory();
    // we don't use RandomIndexWriter because it might add more docvalues than we expect !!!!1
    IndexWriterConfig iwc = newIndexWriterConfig(TEST_VERSION_CURRENT, analyzer);
    iwc.setMergePolicy(newLogMergePolicy());
    IndexWriter iwriter = new IndexWriter(directory, iwc);
    Document doc = new Document();
    byte bytes[] = new byte[100000];
    BytesRef b = new BytesRef(bytes);
    random().nextBytes(bytes);
    doc.add(new SortedDocValuesField("dv", b));
    try {
      iwriter.addDocument(doc);
      fail("did not get expected exception");
    } catch (IllegalArgumentException expected) {
      // expected
    }
    iwriter.close();
    directory.close();
  }

  public void testTooLargeTermSortedSetBytes() throws IOException {
    assumeTrue("codec does not support SORTED_SET", defaultCodecSupportsSortedSet());
    Analyzer analyzer = new MockAnalyzer(random());

    Directory directory = newDirectory();
    // we don't use RandomIndexWriter because it might add more docvalues than we expect !!!!1
    IndexWriterConfig iwc = newIndexWriterConfig(TEST_VERSION_CURRENT, analyzer);
    iwc.setMergePolicy(newLogMergePolicy());
    IndexWriter iwriter = new IndexWriter(directory, iwc);
    Document doc = new Document();
    byte bytes[] = new byte[100000];
    BytesRef b = new BytesRef(bytes);
    random().nextBytes(bytes);
    doc.add(new SortedSetDocValuesField("dv", b));
    try {
      iwriter.addDocument(doc);
      fail("did not get expected exception");
    } catch (IllegalArgumentException expected) {
      // expected
    }
    iwriter.close();
    directory.close();
  }

  // Two documents across segments
  public void testMixedTypesDifferentSegments() throws Exception {
    Directory dir = newDirectory();
    IndexWriter w = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())));
    Document doc = new Document();
    doc.add(new NumericDocValuesField("foo", 0));
    w.addDocument(doc);
    w.commit();

    doc = new Document();
    doc.add(new SortedDocValuesField("foo", new BytesRef("hello")));
    try {
      w.addDocument(doc);
    } catch (IllegalArgumentException iae) {
      // expected
    }
    w.close();
    dir.close();
  }

  // Add inconsistent document after deleteAll
  public void testMixedTypesAfterDeleteAll() throws Exception {
    Directory dir = newDirectory();
    IndexWriter w = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())));
    Document doc = new Document();
    doc.add(new NumericDocValuesField("foo", 0));
    w.addDocument(doc);
    w.deleteAll();

    doc = new Document();
    doc.add(new SortedDocValuesField("foo", new BytesRef("hello")));
    w.addDocument(doc);
    w.close();
    dir.close();
  }

  // Add inconsistent document after reopening IW w/ create
  public void testMixedTypesAfterReopenCreate() throws Exception {
    Directory dir = newDirectory();
    IndexWriter w = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())));
    Document doc = new Document();
    doc.add(new NumericDocValuesField("foo", 0));
    w.addDocument(doc);
    w.close();

    IndexWriterConfig iwc = newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random()));
    iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
    w = new IndexWriter(dir, iwc);
    doc = new Document();
    doc.add(new SortedDocValuesField("foo", new BytesRef("hello")));
    w.addDocument(doc);
    w.close();
    dir.close();
  }

  // Two documents with same field as different types, added
  // from separate threads:
  public void testMixedTypesDifferentThreads() throws Exception {
    Directory dir = newDirectory();
    final IndexWriter w = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())));

    final CountDownLatch startingGun = new CountDownLatch(1);
    final AtomicBoolean hitExc = new AtomicBoolean();
    Thread[] threads = new Thread[3];
    for(int i=0;i<3;i++) {
      Field field;
      if (i == 0) {
        field = new SortedDocValuesField("foo", new BytesRef("hello"));
      } else if (i == 1) {
        field = new NumericDocValuesField("foo", 0);
      } else {
        field = new BinaryDocValuesField("foo", new BytesRef("bazz"));
      }
      final Document doc = new Document();
      doc.add(field);

      threads[i] = new Thread() {
          @Override
          public void run() {
            try {
              startingGun.await();
              w.addDocument(doc);
            } catch (IllegalArgumentException iae) {
              // expected
              hitExc.set(true);
            } catch (Exception e) {
              throw new RuntimeException(e);
            }
          }
        };
      threads[i].start();
    }

    startingGun.countDown();

    for(Thread t : threads) {
      t.join();
    }
    assertTrue(hitExc.get());
    w.close();
    dir.close();
  }

  // Adding documents via addIndexes
  public void testMixedTypesViaAddIndexes() throws Exception {
    Directory dir = newDirectory();
    IndexWriter w = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())));
    Document doc = new Document();
    doc.add(new NumericDocValuesField("foo", 0));
    w.addDocument(doc);

    // Make 2nd index w/ inconsistent field
    Directory dir2 = newDirectory();
    IndexWriter w2 = new IndexWriter(dir2, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())));
    doc = new Document();
    doc.add(new SortedDocValuesField("foo", new BytesRef("hello")));
    w2.addDocument(doc);
    w2.close();

    try {
      w.addIndexes(new Directory[] {dir2});
    } catch (IllegalArgumentException iae) {
      // expected
    }

    IndexReader r = DirectoryReader.open(dir2);
    try {
      w.addIndexes(new IndexReader[] {r});
    } catch (IllegalArgumentException iae) {
      // expected
    }

    r.close();
    dir2.close();
    w.close();
    dir.close();
  }

  public void testIllegalTypeChange() throws Exception {
    Directory dir = newDirectory();
    IndexWriterConfig conf = newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random()));
    IndexWriter writer = new IndexWriter(dir, conf);
    Document doc = new Document();
    doc.add(new NumericDocValuesField("dv", 0L));
    writer.addDocument(doc);
    doc = new Document();
    doc.add(new SortedDocValuesField("dv", new BytesRef("foo")));
    try {
      writer.addDocument(doc);
      fail("did not hit exception");
    } catch (IllegalArgumentException iae) {
      // expected
    }
    writer.close();
    dir.close();
  }

  public void testIllegalTypeChangeAcrossSegments() throws Exception {
    Directory dir = newDirectory();
    IndexWriterConfig conf = newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random()));
    IndexWriter writer = new IndexWriter(dir, conf.clone());
    Document doc = new Document();
    doc.add(new NumericDocValuesField("dv", 0L));
    writer.addDocument(doc);
    writer.close();

    writer = new IndexWriter(dir, conf.clone());
    doc = new Document();
    doc.add(new SortedDocValuesField("dv", new BytesRef("foo")));
    try {
      writer.addDocument(doc);
      fail("did not hit exception");
    } catch (IllegalArgumentException iae) {
      // expected
    }
    writer.close();
    dir.close();
  }

  public void testTypeChangeAfterCloseAndDeleteAll() throws Exception {
    Directory dir = newDirectory();
    IndexWriterConfig conf = newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random()));
    IndexWriter writer = new IndexWriter(dir, conf.clone());
    Document doc = new Document();
    doc.add(new NumericDocValuesField("dv", 0L));
    writer.addDocument(doc);
    writer.close();

    writer = new IndexWriter(dir, conf.clone());
    writer.deleteAll();
    doc = new Document();
    doc.add(new SortedDocValuesField("dv", new BytesRef("foo")));
    writer.addDocument(doc);
    writer.close();
    dir.close();
  }

  public void testTypeChangeAfterDeleteAll() throws Exception {
    Directory dir = newDirectory();
    IndexWriterConfig conf = newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random()));
    IndexWriter writer = new IndexWriter(dir, conf);
    Document doc = new Document();
    doc.add(new NumericDocValuesField("dv", 0L));
    writer.addDocument(doc);
    writer.deleteAll();
    doc = new Document();
    doc.add(new SortedDocValuesField("dv", new BytesRef("foo")));
    writer.addDocument(doc);
    writer.close();
    dir.close();
  }

  public void testTypeChangeAfterCommitAndDeleteAll() throws Exception {
    Directory dir = newDirectory();
    IndexWriterConfig conf = newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random()));
    IndexWriter writer = new IndexWriter(dir, conf);
    Document doc = new Document();
    doc.add(new NumericDocValuesField("dv", 0L));
    writer.addDocument(doc);
    writer.commit();
    writer.deleteAll();
    doc = new Document();
    doc.add(new SortedDocValuesField("dv", new BytesRef("foo")));
    writer.addDocument(doc);
    writer.close();
    dir.close();
  }

  public void testTypeChangeAfterOpenCreate() throws Exception {
    Directory dir = newDirectory();
    IndexWriterConfig conf = newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random()));
    IndexWriter writer = new IndexWriter(dir, conf.clone());
    Document doc = new Document();
    doc.add(new NumericDocValuesField("dv", 0L));
    writer.addDocument(doc);
    writer.close();
    conf.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
    writer = new IndexWriter(dir, conf.clone());
    doc = new Document();
    doc.add(new SortedDocValuesField("dv", new BytesRef("foo")));
    writer.addDocument(doc);
    writer.close();
    dir.close();
  }

  public void testTypeChangeViaAddIndexes() throws Exception {
    Directory dir = newDirectory();
    IndexWriterConfig conf = newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random()));
    IndexWriter writer = new IndexWriter(dir, conf.clone());
    Document doc = new Document();
    doc.add(new NumericDocValuesField("dv", 0L));
    writer.addDocument(doc);
    writer.close();

    Directory dir2 = newDirectory();
    writer = new IndexWriter(dir2, conf.clone());
    doc = new Document();
    doc.add(new SortedDocValuesField("dv", new BytesRef("foo")));
    writer.addDocument(doc);
    try {
      writer.addIndexes(dir);
      fail("did not hit exception");
    } catch (IllegalArgumentException iae) {
      // expected
    }
    writer.close();

    dir.close();
    dir2.close();
  }

  public void testTypeChangeViaAddIndexesIR() throws Exception {
    Directory dir = newDirectory();
    IndexWriterConfig conf = newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random()));
    IndexWriter writer = new IndexWriter(dir, conf.clone());
    Document doc = new Document();
    doc.add(new NumericDocValuesField("dv", 0L));
    writer.addDocument(doc);
    writer.close();

    Directory dir2 = newDirectory();
    writer = new IndexWriter(dir2, conf.clone());
    doc = new Document();
    doc.add(new SortedDocValuesField("dv", new BytesRef("foo")));
    writer.addDocument(doc);
    IndexReader[] readers = new IndexReader[] {DirectoryReader.open(dir)};
    try {
      writer.addIndexes(readers);
      fail("did not hit exception");
    } catch (IllegalArgumentException iae) {
      // expected
    }
    readers[0].close();
    writer.close();

    dir.close();
    dir2.close();
  }

  public void testTypeChangeViaAddIndexes2() throws Exception {
    Directory dir = newDirectory();
    IndexWriterConfig conf = newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random()));
    IndexWriter writer = new IndexWriter(dir, conf.clone());
    Document doc = new Document();
    doc.add(new NumericDocValuesField("dv", 0L));
    writer.addDocument(doc);
    writer.close();

    Directory dir2 = newDirectory();
    writer = new IndexWriter(dir2, conf.clone());
    writer.addIndexes(dir);
    doc = new Document();
    doc.add(new SortedDocValuesField("dv", new BytesRef("foo")));
    try {
      writer.addDocument(doc);
      fail("did not hit exception");
    } catch (IllegalArgumentException iae) {
      // expected
    }
    writer.close();
    dir2.close();
    dir.close();
  }

  public void testTypeChangeViaAddIndexesIR2() throws Exception {
    Directory dir = newDirectory();
    IndexWriterConfig conf = newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random()));
    IndexWriter writer = new IndexWriter(dir, conf.clone());
    Document doc = new Document();
    doc.add(new NumericDocValuesField("dv", 0L));
    writer.addDocument(doc);
    writer.close();

    Directory dir2 = newDirectory();
    writer = new IndexWriter(dir2, conf.clone());
    IndexReader[] readers = new IndexReader[] {DirectoryReader.open(dir)};
    writer.addIndexes(readers);
    readers[0].close();
    doc = new Document();
    doc.add(new SortedDocValuesField("dv", new BytesRef("foo")));
    try {
      writer.addDocument(doc);
      fail("did not hit exception");
    } catch (IllegalArgumentException iae) {
      // expected
    }
    writer.close();
    dir2.close();
    dir.close();
  }

  public void testDocsWithField() throws Exception {
    Directory dir = newDirectory();
    IndexWriterConfig conf = newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random()));
    IndexWriter writer = new IndexWriter(dir, conf);
    Document doc = new Document();
    doc.add(new NumericDocValuesField("dv", 0L));
    writer.addDocument(doc);

    doc = new Document();
    doc.add(new TextField("dv", "some text", Field.Store.NO));
    doc.add(new NumericDocValuesField("dv", 0L));
    writer.addDocument(doc);

    DirectoryReader r = writer.getReader();
    writer.close();

    AtomicReader subR = r.leaves().get(0).reader();
    assertEquals(2, subR.numDocs());

    Bits bits = FieldCache.DEFAULT.getDocsWithField(subR, "dv");
    assertTrue(bits.get(0));
    assertTrue(bits.get(1));
    r.close();
    dir.close();
  }

  public void testSameFieldNameForPostingAndDocValue() throws Exception {
    // LUCENE-5192: FieldInfos.Builder neglected to update
    // globalFieldNumbers.docValuesType map if the field existed, resulting in
    // potentially adding the same field with different DV types.
    Directory dir = newDirectory();
    IndexWriterConfig conf = newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random()));
    IndexWriter writer = new IndexWriter(dir, conf);

    Document doc = new Document();
    doc.add(new StringField("f", "mock-value", Store.NO));
    doc.add(new NumericDocValuesField("f", 5));
    writer.addDocument(doc);
    writer.commit();

    doc = new Document();
    doc.add(new BinaryDocValuesField("f", new BytesRef("mock")));
    try {
      writer.addDocument(doc);
      fail("should not have succeeded to add a field with different DV type than what already exists");
    } catch (IllegalArgumentException e) {
      writer.rollback();
    }

    dir.close();
  }

}


text:
package com.allanbank.mongodb.builder.write;

import javax.annotation.concurrent.Immutable;
import javax.annotation.concurrent.ThreadSafe;

import com.allanbank.mongodb.bson.Document;
import com.allanbank.mongodb.bson.DocumentAssignable;

/**
 * UpdateOperation provides a container for the fields in an update request.
 *
 * @api.yes This class is part of the driver's API. Public and protected members
 *          will be deprecated for at least 1 non-bugfix release (version
 *          numbers are <major>.<minor>.<bugfix>) before being
 *          removed or modified.
 * @copyright 2014, Allanbank Consulting, Inc., All Rights Reserved
 */
@Immutable
@ThreadSafe
public class UpdateOperation
        implements WriteOperation {

    /** Serialization version for the class. */
    private static final long serialVersionUID = 4657279430768594366L;

    /** If true then the update can modify multiple documents. */
    private final boolean myMultiUpdate;

    /** The query to find the documents to update. */
    private final Document myQuery;

    /** The update specification. */
    private final Document myUpdate;

    /** If true then the document should be inserted if not found. */
    private final boolean myUpsert;

    /**
     * Creates a new UpdateOperation.
     *
     * @param query
     *            The query to find the documents to update.
     * @param update
     *            The update specification.
     * @param multiUpdate
     *            If true then the update is applied to all of the matching
     *            documents, otherwise only the first document found is updated.
     * @param upsert
     *            If true then if no document is found then a new document is
     *            created and updated, otherwise no operation is performed.
     */
    public UpdateOperation(final DocumentAssignable query,
            final DocumentAssignable update, final boolean multiUpdate,
            final boolean upsert) {
        myQuery = query.asDocument();
        myUpdate = update.asDocument();
        myUpsert = upsert;
        myMultiUpdate = multiUpdate;
    }

    /**
     * Determines if the passed object is of this same type as this object and
     * if so that its fields are equal.
     *
     * @param object
     *            The object to compare to.
     *
     * @see Object#equals(Object)
     */
    @Override
    public boolean equals(final Object object) {
        boolean result = false;
        if (this == object) {
            result = true;
        }
        else if ((object != null) && (getClass() == object.getClass())) {
            final UpdateOperation other = (UpdateOperation) object;

            result = (myUpsert == other.myUpsert)
                    && (myMultiUpdate == other.myMultiUpdate)
                    && myQuery.equals(other.myQuery)
                    && myUpdate.equals(other.myUpdate);
        }
        return result;
    }

    /**
     * Returns the query to find the documents to update.
     *
     * @return The query to find the documents to update.
     */
    public Document getQuery() {
        return myQuery;
    }

    /**
     * {@inheritDoc}
     *

     * Overridden to return the query for the update.
     *

     */
    @Override
    public Document getRoutingDocument() {
        return myQuery;
    }

    /**
     * {@inheritDoc}
     *

     * Overridden to return {@link WriteOperationType#UPDATE}.
     *

     */
    @Override
    public final WriteOperationType getType() {
        return WriteOperationType.UPDATE;
    }

    /**
     * Returns the update specification.
     *
     * @return The update specification.
     */
    public Document getUpdate() {
        return myUpdate;
    }

    /**
     * Computes a reasonable hash code.
     *
     * @return The hash code value.
     */
    @Override
    public int hashCode() {
        int result = 1;
        result = (31 * result) + (myUpsert ? 31 : 11);
        result = (31 * result) + (myMultiUpdate ? 31 : 11);
        result = (31 * result) + myQuery.hashCode();
        result = (31 * result) + myUpdate.hashCode();
        return result;
    }

    /**
     * Returns true if the update can modify multiple documents.
     *
     * @return True if the update can modify multiple documents.
     */
    public boolean isMultiUpdate() {
        return myMultiUpdate;
    }

    /**
     * Returns true if the document should be inserted if not found.
     *
     * @return True if the document should be inserted if not found.
     */
    public boolean isUpsert() {
        return myUpsert;
    }

    /**
     * {@inheritDoc}
     *

     * Overridden to returns a representation of the update.
     *

     */
    @Override
    public String toString() {
        return "Update[upsert=" + myUpsert + ",multi=" + myMultiUpdate
                + ",query=" + myQuery + ",update=" + myUpdate + "]";
    }
}


text:
const toPairs = require('lodash/toPairs');
const logging = require('../../../../../shared/logging');

/*
 * @param from: object with a SINGLE entry { 'fromColumn': 'fromValue' }
 * @param to: object with a SINGLE entry { 'toColumn': 'toValue' }
 */
const createColumnToColumnMap = ({from, to, tableName}) => (connection) => {
    return connection.schema.hasTable(tableName)
        .then((tableExists) => {
            if (!tableExists) {
                logging.warn(
                    `Table ${tableName} does not exist`
                );
                return;
            }

            const [fromColumn, fromValue] = toPairs(from)[0];
            const [toColumn, toValue] = toPairs(to)[0];

            return Promise.all([
                connection.schema.hasColumn(tableName, fromColumn),
                connection.schema.hasColumn(tableName, toColumn)
            ]).then(([fromColumnExists, toColumnExists]) => {
                if (!fromColumnExists) {
                    logging.warn(
                        `Table '${tableName}' does not have column '${fromColumn}'`
                    );
                }
                if (!toColumnExists) {
                    logging.warn(
                        `Table '${tableName}' does not have column '${toColumn}'`
                    );
                }
                if (!fromColumnExists || !toColumnExists) {
                    return;
                }

                logging.info(
                    `Updating ${tableName}, setting "${toColumn}" column to "${toValue}" where "${fromColumn}" column is "${fromValue}"`
                );

                return connection(tableName)
                    .where(fromColumn, fromValue)
                    .update(toColumn, toValue);
            });
        });
};

const createColumnToColumnMigration = ({tableName, from, to}) => {
    return {
        up: createColumnToColumnMap({from, to, tableName}),
        down: createColumnToColumnMap({from: to, to: from, tableName})
    };
};

const typeColumnToPageTrue = createColumnToColumnMigration({
    tableName: 'posts',
    from: {
        type: 'page'
    },
    to: {
        page: true
    }
});

const typeColumnToPageFalse = createColumnToColumnMigration({
    tableName: 'posts',
    from: {
        type: 'post'
    },
    to: {
        page: false
    }
});

module.exports.up = ({transacting}) => {
    return transacting.schema.hasColumn('posts', 'type').then((hasTypeColumn) => {
        if (!hasTypeColumn) {
            // no-op'd post.page->post.type migrations were never run
            return Promise.resolve();
        }

        return Promise.all([
            typeColumnToPageTrue.up(transacting),
            typeColumnToPageFalse.up(transacting)
        ]);
    });
};

// `up` only runs in order to fix a previous migration so we don't want to do
// anything in `down` because it would put previously-fine sites into the wrong
// state
module.exports.down = () => Promise.resolve();

module.exports.config = {
    transaction: true
};


text:
package docker

import (
	"fmt"
	"io"

	"github.com/coreos/mantle/kola/register"
	"github.com/coreos/mantle/lang/worker"
	"github.com/coreos/mantle/platform"
	"github.com/coreos/mantle/system/exec"
	"github.com/coreos/mantle/system/targen"

	"github.com/coreos/mantle/Godeps/_workspace/src/github.com/coreos/go-semver/semver"
	"github.com/coreos/mantle/Godeps/_workspace/src/github.com/coreos/pkg/capnslog"
	"github.com/coreos/mantle/Godeps/_workspace/src/golang.org/x/net/context"
)

var (
	plog = capnslog.NewPackageLogger("github.com/coreos/mantle", "kola/tests/docker")
)

func init() {
	register.Register(&register.Test{
		Run:         dockerResources,
		ClusterSize: 1,
		NativeFuncs: map[string]func() error{
			"sleepcontainer": func() error {
				return genDockerContainer("sleep", []string{"sleep"})
			},
		},
		Name:     "docker.resources",
		UserData: `#cloud-config`,
		// began shipping docker 1.10 in 949, which has all of the
		// tested resource options.
		MinVersion: semver.Version{Major: 949},
	})
}

// executed on the target vm to make a docker container out of binaries on the host
func genDockerContainer(name string, binnames []string) error {
	tg := targen.New()

	for _, bin := range binnames {
		binpath, err := exec.LookPath(bin)
		if err != nil {
			return fmt.Errorf("failed to find %q binary: %v", bin, err)
		}

		tg.AddBinary(binpath)
	}

	pr, pw := io.Pipe()
	dimport := exec.Command("docker", "import", "-", name)
	dimport.Stdin = pr

	if err := dimport.Start(); err != nil {
		return fmt.Errorf("starting docker import failed %v", err)
	}

	if err := tg.Generate(pw); err != nil {
		return fmt.Errorf("failed to generate tarball: %v", err)
	}

	// err is always nil.
	_ = pw.Close()

	if err := dimport.Wait(); err != nil {
		return fmt.Errorf("waiting for docker import failed %v", err)
	}

	return nil
}

// using a simple container, exercise various docker options that set resource
// limits. also acts as a regression test for
// https://github.com/coreos/bugs/issues/1246.
func dockerResources(c platform.TestCluster) error {
	m := c.Machines()[0]

	plog.Debug("creating sleep container")

	if err := c.RunNative("sleepcontainer", m); err != nil {
		return fmt.Errorf("failed to create sleep container: %v", err)
	}

	dockerFmt := "docker run --rm %s sleep sleep 0.2"

	dCmd := func(arg string) string {
		return fmt.Sprintf(dockerFmt, arg)
	}

	ctx := context.Background()
	wg := worker.NewWorkerGroup(ctx, 10)

	// ref https://docs.docker.com/engine/reference/run/#runtime-constraints-on-resources
	for _, dockerCmd := range []string{
		// must set memory when setting memory-swap
		dCmd("--memory=10m --memory-swap=10m"),
		dCmd("--memory-reservation=10m"),
		dCmd("--kernel-memory=10m"),
		dCmd("--cpu-shares=100"),
		dCmd("--cpu-period=1000"),
		dCmd("--cpuset-cpus=0"),
		dCmd("--cpuset-mems=0"),
		dCmd("--cpu-quota=1000"),
		dCmd("--blkio-weight=10"),
		// none of these work in QEMU due to apparent lack of cfq for
		// blkio in virtual block devices.
		//dCmd("--blkio-weight-device=/dev/vda:10"),
		//dCmd("--device-read-bps=/dev/vda:1kb"),
		//dCmd("--device-write-bps=/dev/vda:1kb"),
		//dCmd("--device-read-iops=/dev/vda:10"),
		//dCmd("--device-write-iops=/dev/vda:10"),
		dCmd("--memory=10m --oom-kill-disable=true"),
		dCmd("--memory-swappiness=50"),
		dCmd("--shm-size=1m"),
	} {
		plog.Debugf("Executing %q", dockerCmd)

		// lol closures
		cmd := dockerCmd

		worker := func(c context.Context) error {
			// TODO: pass context thru to SSH
			output, err := m.SSH(cmd)
			if err != nil {
				return fmt.Errorf("failed to run %q: output: %q status: %q", dockerCmd, output, err)
			}
			return nil
		}

		if err := wg.Start(worker); err != nil {
			return wg.WaitError(err)
		}
	}

	return wg.Wait()
}


text:
<?php namespace BTorrent;

class Dir implements \JsonSerializable {
	public $name = null;
	public $subdirs = array();
	public $files = array();

	public function __construct($name)
	{
		$this->name = $name;
	}

	public function &addFile(File &$file)
	{
		$this->files[] = &$file;
		return $file;
	}

	public function &addDir(Dir &$dir)
	{
		$this->subdirs[] = &$dir;
		return $dir;
	}

	public function &findDir($name)
	{
		$foundDir = false;
		foreach ($this->subdirs as $subdir) {
			if ($subdir->name == $name) {
				$foundDir = &$subdir;
				break;
			}
		}
		return $foundDir;
	}

	public function jsonSerialize()
	{
		return array(
			'name' => $this->name,
			'children' => array_merge($this->subdirs, $this->files),
			'open' => true,
		);
	}
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.people.v1.model;

/**
 * A result of a search query.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the People API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class SearchResult extends com.google.api.client.json.GenericJson {

  /**
   * The matched Person.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private Person person;

  /**
   * The matched Person.
   * @return value or {@code null} for none
   */
  public Person getPerson() {
    return person;
  }

  /**
   * The matched Person.
   * @param person person or {@code null} for none
   */
  public SearchResult setPerson(Person person) {
    this.person = person;
    return this;
  }

  @Override
  public SearchResult set(String fieldName, Object value) {
    return (SearchResult) super.set(fieldName, value);
  }

  @Override
  public SearchResult clone() {
    return (SearchResult) super.clone();
  }

}


text:
package org.apache.ignite.internal.processors.query.calcite.schema;

import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.function.Function;
import java.util.function.Predicate;
import org.apache.calcite.plan.RelOptCluster;
import org.apache.calcite.plan.RelOptTable;
import org.apache.calcite.rel.RelCollation;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rex.RexNode;
import org.apache.calcite.util.ImmutableBitSet;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.IgniteException;
import org.apache.ignite.internal.cache.query.index.Index;
import org.apache.ignite.internal.cache.query.index.sorted.inline.IndexQueryContext;
import org.apache.ignite.internal.cache.query.index.sorted.inline.InlineIndex;
import org.apache.ignite.internal.cache.query.index.sorted.inline.InlineIndexImpl;
import org.apache.ignite.internal.processors.query.calcite.exec.ExecutionContext;
import org.apache.ignite.internal.processors.query.calcite.exec.IndexFirstLastScan;
import org.apache.ignite.internal.processors.query.calcite.exec.IndexScan;
import org.apache.ignite.internal.processors.query.calcite.exec.exp.RangeIterable;
import org.apache.ignite.internal.processors.query.calcite.metadata.ColocationGroup;
import org.apache.ignite.internal.processors.query.calcite.prepare.bounds.SearchBounds;
import org.apache.ignite.internal.processors.query.calcite.rel.logical.IgniteLogicalIndexScan;
import org.apache.ignite.internal.processors.query.calcite.util.Commons;
import org.apache.ignite.internal.processors.query.calcite.util.RexUtils;
import org.apache.ignite.spi.indexing.IndexingQueryFilter;
import org.apache.ignite.spi.indexing.IndexingQueryFilterImpl;
import org.jetbrains.annotations.Nullable;

/**
 * Ignite scannable cache index.
 */
public class CacheIndexImpl implements IgniteIndex {
    /** */
    private final RelCollation collation;

    /** */
    private final String idxName;

    /** */
    private final @Nullable Index idx;

    /** */
    private final IgniteCacheTable tbl;

    /** */
    public CacheIndexImpl(RelCollation collation, String name, @Nullable Index idx, IgniteCacheTable tbl) {
        this.collation = collation;
        idxName = name;
        this.idx = idx;
        this.tbl = tbl;
    }

    /** */
    @Override public RelCollation collation() {
        return collation;
    }

    /** */
    @Override public String name() {
        return idxName;
    }

    /** */
    @Override public IgniteTable table() {
        return tbl;
    }

    /** Underlying query index. */
    public Index queryIndex() {
        return idx;
    }

    /** {@inheritDoc} */
    @Override public IgniteLogicalIndexScan toRel(
        RelOptCluster cluster,
        RelOptTable relOptTbl,
        @Nullable List<RexNode> proj,
        @Nullable RexNode cond,
        @Nullable ImmutableBitSet requiredColumns
    ) {
        return IgniteLogicalIndexScan.create(cluster, cluster.traitSet(), relOptTbl, idxName, proj, cond, requiredColumns);
    }

    /** */
    @Override public <Row> Iterable<Row> scan(
        ExecutionContext<Row> execCtx,
        ColocationGroup group,
        Predicate<Row> filters,
        RangeIterable<Row> ranges,
        Function<Row, Row> rowTransformer,
        @Nullable ImmutableBitSet requiredColumns
    ) {
        UUID localNodeId = execCtx.localNodeId();
        if (group.nodeIds().contains(localNodeId) && idx != null) {
            return new IndexScan<>(execCtx, tbl.descriptor(), idx.unwrap(InlineIndex.class), collation.getKeys(),
                group.partitions(localNodeId), filters, ranges, rowTransformer, requiredColumns);
        }

        return Collections.emptyList();
    }

    /** {@inheritDoc} */
    @Override public <Row> Iterable<Row> firstOrLast(
        boolean first,
        ExecutionContext<Row> ectx,
        ColocationGroup grp,
        @Nullable ImmutableBitSet requiredColumns
    ) {
        UUID localNodeId = ectx.localNodeId();

        if (grp.nodeIds().contains(localNodeId) && idx != null) {
            return new IndexFirstLastScan<>(
                first,
                ectx,
                tbl.descriptor(),
                idx.unwrap(InlineIndexImpl.class),
                collation.getKeys(),
                grp.partitions(localNodeId),
                requiredColumns
            );
        }

        return Collections.emptyList();
    }

    /** {@inheritDoc} */
    @Override public long count(ExecutionContext<?> ectx, ColocationGroup grp) {
        long cnt = 0;

        if (idx != null && grp.nodeIds().contains(ectx.localNodeId())) {
            IndexingQueryFilter filter = new IndexingQueryFilterImpl(tbl.descriptor().cacheContext().kernalContext(),
                ectx.topologyVersion(), grp.partitions(ectx.localNodeId()));

            InlineIndex iidx = idx.unwrap(InlineIndex.class);

            try {
                for (int i = 0; i < iidx.segmentsCount(); ++i)
                    cnt += iidx.count(i, new IndexQueryContext(filter, null, ectx.mvccSnapshot()));
            }
            catch (IgniteCheckedException e) {
                throw new IgniteException("Unable to count index records.", e);
            }
        }

        return cnt;
    }

    /** {@inheritDoc} */
    @Override public List<SearchBounds> toSearchBounds(
        RelOptCluster cluster,
        @Nullable RexNode cond,
        @Nullable ImmutableBitSet requiredColumns
    ) {
        RelCollation collation = this.collation;
        RelDataType rowType = tbl.getRowType(cluster.getTypeFactory());

        if (requiredColumns != null)
            collation = collation.apply(Commons.mapping(requiredColumns, rowType.getFieldCount()));

        if (!collation.getFieldCollations().isEmpty()) {
            return RexUtils.buildSortedSearchBounds(
                cluster,
                collation,
                cond,
                rowType,
                requiredColumns
            );
        }

        // Empty index find predicate.
        return null;
    }
}


text:
var PanelCollection = Backbone.Collection.extend({
	model: PanelModel,
	url: 'data/panels.json'
});


text:
exports.installDependencies = function() {
  return require('atom-package-deps')
    .install('ide-purescript');
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Gitatouille</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_git_manual">Git manual</string>
    <string name="menu_git_tutorial">Git tutorial</string>
    <string name="menu_git_tricks">Git tricks</string>
    <string name="menu_git_articles">Git articles</string>
    <string name="menu_favorites">Favorites</string>
    <string name="menu_about_us">About us</string>
    <string name="menu_exit">Exit</string>
</resources>


text:
typedef void (^CLMConstructingBodyWithBlock)(id <AFMultipartFormData> formData);

@interface CLMNetworkingClient : NSObject

@property (nonatomic, readonly) AFHTTPRequestOperationManager *manager;
@property (nonatomic, readonly) CLMFilter *filter;

#pragma mark - Initializer

- (instancetype)initWithManager:(AFHTTPRequestOperationManager *)manager;

#pragma mark - Public - GET

- (BFTask *)GET:(NSString *)URLString parameters:(id)parameters;

#pragma mark - Public - HEAD

- (BFTask *)HEAD:(NSString *)URLString parameters:(id)parameters;

#pragma mark - Public - POST

- (BFTask *)POST:(NSString *)URLString parameters:(id)parameters;
- (BFTask *)POST:(NSString *)URLString parameters:(id)parameters constructingBodyWithBlock:(CLMConstructingBodyWithBlock)block;

#pragma mark - Public - PUT

- (BFTask *)PUT:(NSString *)URLString parameters:(id)parameters;
- (BFTask *)PUT:(NSString *)URLString parameters:(id)parameters constructingBodyWithBlock:(CLMConstructingBodyWithBlock)block;

#pragma mark - Public - PATCH

- (BFTask *)PATCH:(NSString *)URLString parameters:(id)parameters;
- (BFTask *)PATCH:(NSString *)URLString parameters:(id)parameters constructingBodyWithBlock:(CLMConstructingBodyWithBlock)block;

#pragma mark - Public - DELETE

- (BFTask *)DELETE:(NSString *)URLString parameters:(id)parameters;

#pragma mark - Public

- (void)cancelAll;

- (BFTask *)requestTaskWithHTTPMethod:(NSString *)method
                            URLString:(NSString *)URLString
                           parameters:(id)parameters
            constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block;

@end


text:
require "test_helper"

class EncryptedFormFieldsTest < MiniTest::Unit::TestCase
  def test_encrypting_parameters
    hash = EncryptedFormFields.encrypt_parameters("foo" => "bar")
    decrypted = EncryptedFormFields.decrypt_and_verify(hash["foo"])
    assert_equal("bar", decrypted)
  end

  def test_decrypting_parameters
    value = EncryptedFormFields.encrypt_and_sign("bar")
    hash = EncryptedFormFields.decrypt_parameters("foo" => { "0" => value })
    assert_equal("bar", hash["foo"]["0"])
  end
end


text:
<?php

namespace Rezzza\Jobflow\Extension\ETL\Processor;

use Knp\ETL\ContextInterface;
use Knp\ETL\TransformerInterface;
use Psr\Log\LoggerInterface;
use Rezzza\Jobflow\Metadata\MetadataAccessor;
use Rezzza\Jobflow\Processor\JobProcessor;
use Rezzza\Jobflow\Scheduler\ExecutionContext;

class TransformerProxy extends ETLProcessor implements TransformerInterface, JobProcessor
{
    public function __construct(TransformerInterface $processor, MetadataAccessor $metadataAccessor, LoggerInterface $logger = null)
    {
        // Construct used for TypeHinting
        parent::__construct($processor, $metadataAccessor, $logger);
    }

    public function transform($data, ContextInterface $context)
    {
        return $this->processor->transform($data, $context);
    }

    public function execute(ExecutionContext $execution)
    {
        $data = $execution->read();

        $this->debug(count($data) .' rows');

        foreach ($data as $k => $result) {
            $value = $result->getValue();
            $metadata = $result->getMetadata();
            $context = $this->createContext($execution, $metadata);

            $transformedData = $this->transform($value, $context);

            if (is_array($transformedData)) {
                foreach ($transformedData as $d) {
                    $this->writeData($value, $metadata, $execution, $d);
                }
            } else {
                $this->writeData($value, $metadata, $execution, $transformedData);
            }
        }

        $execution->valid();
    }

    private function writeData($value, $metadata, $execution, $data)
    {
        $metadata = $this->metadataAccessor->createMetadata($value, $metadata);
        $execution->write($data, $metadata);
    }
}


text:
package io.github.cfactorcomputing.odin.core.bootstrap.cd;

import java.util.Map;

/**
 * @author gibugeorge on 11/12/16.
 * @version 1.0
 */
public class RuntimeConfiguration {

    private final Map<String, Object> configurations;

    public RuntimeConfiguration(final Map<String, Object> configurations) {
        this.configurations = configurations;
    }

    public Map<String, Object> getConfigurations() {
        return configurations;
    }
}


text:
/**@file
 * @defgroup ant_hrm_rx_example ANT HRM RX example
 * @{
 * @ingroup nrf_ant_hrm
 *
 * @brief Example of ANT HRM RX profile.
 *
 * Before compiling this example for NRF52, complete the following steps:
 * - Download the S212 SoftDevice from thisisant.com.
 * - Extract the downloaded zip file and copy the S212 SoftDevice headers to <tt>\<InstallFolder\>/components/softdevice/s212/headers</tt>.
 * If you are using Keil packs, copy the files into a @c headers folder in your example folder.
 * - Make sure that @ref ANT_LICENSE_KEY in @c nrf_sdm.h is uncommented.
 */

#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include "app_error.h"
#include "nrf.h"
#include "nrf_sdm.h"
#include "bsp.h"
#include "hardfault.h"
#include "app_timer.h"
#include "nordic_common.h"
#include "ant_stack_config.h"
#include "softdevice_handler.h"
#include "ant_hrm.h"
#include "ant_key_manager.h"
#include "ant_state_indicator.h"
#include "bsp_btn_ant.h"

#define NRF_LOG_MODULE_NAME "APP"
#include "nrf_log.h"
#include "nrf_log_ctrl.h"

#define APP_TIMER_PRESCALER         0x00 /**< Value of the RTC1 PRESCALER register. */
#define APP_TIMER_OP_QUEUE_SIZE     0x04 /**< Size of timer operation queues. */

#define HRM_CHANNEL_NUMBER          0x00 /**< Channel number assigned to HRM profile. */

#define WILDCARD_TRANSMISSION_TYPE  0x00 /**< Wildcard transmission type. */
#define WILDCARD_DEVICE_NUMBER      0x00 /**< Wildcard device number. */

#define ANTPLUS_NETWORK_NUMBER      0x00 /**< Network number. */

/** @snippet [ANT HRM RX Instance] */
HRM_DISP_CHANNEL_CONFIG_DEF(m_ant_hrm,
                            HRM_CHANNEL_NUMBER,
                            WILDCARD_TRANSMISSION_TYPE,
                            WILDCARD_DEVICE_NUMBER,
                            ANTPLUS_NETWORK_NUMBER,
                            HRM_MSG_PERIOD_4Hz);
ant_hrm_profile_t m_ant_hrm;
/** @snippet [ANT HRM RX Instance] */

/**@brief Function for dispatching a ANT stack event to all modules with a ANT stack event handler.
 *
 * @details This function is called from the ANT Stack event interrupt handler after a ANT stack
 *          event has been received.
 *
 * @param[in] p_ant_evt  ANT stack event.
 */
void ant_evt_dispatch(ant_evt_t * p_ant_evt)
{
    ant_hrm_disp_evt_handler(&m_ant_hrm, p_ant_evt);
    ant_state_indicator_evt_handler(p_ant_evt);
    bsp_btn_ant_on_ant_evt(p_ant_evt);
}

static void ant_hrm_evt_handler(ant_hrm_profile_t * p_profile, ant_hrm_evt_t event)
{
    switch (event)
    {
        case ANT_HRM_PAGE_0_UPDATED:
            /* fall through */
        case ANT_HRM_PAGE_1_UPDATED:
            /* fall through */
        case ANT_HRM_PAGE_2_UPDATED:
            /* fall through */
        case ANT_HRM_PAGE_3_UPDATED:
            /* fall through */
        case ANT_HRM_PAGE_4_UPDATED:
            NRF_LOG_INFO("Page was updated\r\n");
            break;

        default:
            break;
    }
}

/**@brief Function for handling events from the BSP module.
 *
 * @param[in]   event   Event generated by BSP.
 */
void bsp_event_handler(bsp_event_t event)
{
    switch (event)
    {
        case BSP_EVENT_SLEEP:
            ant_state_indicator_sleep_mode_enter();
            break;

        default:
            break;
    }
}

/**@brief Function for the Timer, Tracer and BSP initialization.
 */
static void utils_setup(void)
{
    uint32_t err_code;

    err_code = NRF_LOG_INIT(NULL);
    APP_ERROR_CHECK(err_code);

    APP_TIMER_INIT(APP_TIMER_PRESCALER, APP_TIMER_OP_QUEUE_SIZE, false);

    err_code = bsp_init(BSP_INIT_LED | BSP_INIT_BUTTONS,
                        APP_TIMER_TICKS(100, APP_TIMER_PRESCALER),
                        bsp_event_handler);
    APP_ERROR_CHECK(err_code);

    err_code = bsp_btn_ant_init();
    APP_ERROR_CHECK(err_code);
}

/**@brief Function for ANT stack initialization.
 *
 * @details Initializes the SoftDevice and the ANT event interrupt.
 */
static void softdevice_setup(void)
{
    uint32_t err_code;

    nrf_clock_lf_cfg_t clock_lf_cfg = NRF_CLOCK_LFCLKSRC;

    err_code = softdevice_ant_evt_handler_set(ant_evt_dispatch);
    APP_ERROR_CHECK(err_code);

    err_code = softdevice_handler_init(&clock_lf_cfg, NULL, 0, NULL);
    APP_ERROR_CHECK(err_code);

    err_code = ant_stack_static_config();
    APP_ERROR_CHECK(err_code);

    err_code = ant_plus_key_set(ANTPLUS_NETWORK_NUMBER);
    APP_ERROR_CHECK(err_code);
}

/**@brief Function for HRM profile initialization.
 *
 * @details Initializes the HRM profile and open ANT channel.
 */
static void profile_setup(void)
{
/** @snippet [ANT HRM RX Profile Setup] */
    uint32_t err_code;

    err_code = ant_hrm_disp_init(&m_ant_hrm,
                                 HRM_DISP_CHANNEL_CONFIG(m_ant_hrm),
                                 ant_hrm_evt_handler);
    APP_ERROR_CHECK(err_code);

    err_code = ant_hrm_disp_open(&m_ant_hrm);
    APP_ERROR_CHECK(err_code);

    err_code = ant_state_indicator_channel_opened();
    APP_ERROR_CHECK(err_code);
/** @snippet [ANT HRM RX Profile Setup] */
}

/**@brief Function for application main entry, does not return.
 */
int main(void)
{
    uint32_t err_code;

    utils_setup();
    softdevice_setup();
    ant_state_indicator_init(m_ant_hrm.channel_number, HRM_DISP_CHANNEL_TYPE);
    profile_setup();

    for (;;)
    {
        if (NRF_LOG_PROCESS() == false)
        {
            err_code = sd_app_evt_wait();
            APP_ERROR_CHECK(err_code);
        }
    }
}

/**
 *@}
 **/


text:
package bsoncore

import (
	"bytes"
	"errors"
	"fmt"
	"io"
	"strconv"

	"github.com/go-stack/stack"
	"go.mongodb.org/mongo-driver/bson/bsontype"
)

// ValidationError is an error type returned when attempting to validate a document or array.
type ValidationError string

func (ve ValidationError) Error() string { return string(ve) }

// NewDocumentLengthError creates and returns an error for when the length of a document exceeds the
// bytes available.
func NewDocumentLengthError(length, rem int) error {
	return lengthError("document", length, rem)
}

func lengthError(bufferType string, length, rem int) error {
	return ValidationError(fmt.Sprintf("%v length exceeds available bytes. length=%d remainingBytes=%d",
		bufferType, length, rem))
}

// InsufficientBytesError indicates that there were not enough bytes to read the next component.
type InsufficientBytesError struct {
	Source    []byte
	Remaining []byte
	Stack     stack.CallStack
}

// NewInsufficientBytesError creates a new InsufficientBytesError with the given Document, remaining
// bytes, and the current stack.
func NewInsufficientBytesError(src, rem []byte) InsufficientBytesError {
	return InsufficientBytesError{Source: src, Remaining: rem, Stack: stack.Trace().TrimRuntime()}
}

// Error implements the error interface.
func (ibe InsufficientBytesError) Error() string {
	return "too few bytes to read next component"
}

// ErrorStack returns a string representing the stack at the point where the error occurred.
func (ibe InsufficientBytesError) ErrorStack() string {
	s := bytes.NewBufferString("too few bytes to read next component: [")

	for i, call := range ibe.Stack {
		if i != 0 {
			s.WriteString(", ")
		}

		// go vet doesn't like %k even though it's part of stack's API, so we move the format
		// string so it doesn't complain. (We also can't make it a constant, or go vet still
		// complains.)
		callFormat := "%k.%n %v"

		s.WriteString(fmt.Sprintf(callFormat, call, call, call))
	}

	s.WriteRune(']')

	return s.String()
}

// Equal checks that err2 also is an ErrTooSmall.
func (ibe InsufficientBytesError) Equal(err2 error) bool {
	switch err2.(type) {
	case InsufficientBytesError:
		return true
	default:
		return false
	}
}

// InvalidDepthTraversalError is returned when attempting a recursive Lookup when one component of
// the path is neither an embedded document nor an array.
type InvalidDepthTraversalError struct {
	Key  string
	Type bsontype.Type
}

func (idte InvalidDepthTraversalError) Error() string {
	return fmt.Sprintf(
		"attempt to traverse into %s, but it's type is %s, not %s nor %s",
		idte.Key, idte.Type, bsontype.EmbeddedDocument, bsontype.Array,
	)
}

// ErrMissingNull is returned when a document or array's last byte is not null.
const ErrMissingNull ValidationError = "document or array end is missing null byte"

// ErrInvalidLength indicates that a length in a binary representation of a BSON document or array
// is invalid.
const ErrInvalidLength ValidationError = "document or array length is invalid"

// ErrNilReader indicates that an operation was attempted on a nil io.Reader.
var ErrNilReader = errors.New("nil reader")

// ErrEmptyKey indicates that no key was provided to a Lookup method.
var ErrEmptyKey = errors.New("empty key provided")

// ErrElementNotFound indicates that an Element matching a certain condition does not exist.
var ErrElementNotFound = errors.New("element not found")

// ErrOutOfBounds indicates that an index provided to access something was invalid.
var ErrOutOfBounds = errors.New("out of bounds")

// Document is a raw bytes representation of a BSON document.
type Document []byte

// NewDocumentFromReader reads a document from r. This function will only validate the length is
// correct and that the document ends with a null byte.
func NewDocumentFromReader(r io.Reader) (Document, error) {
	return newBufferFromReader(r)
}

func newBufferFromReader(r io.Reader) ([]byte, error) {
	if r == nil {
		return nil, ErrNilReader
	}

	var lengthBytes [4]byte

	// ReadFull guarantees that we will have read at least len(lengthBytes) if err == nil
	_, err := io.ReadFull(r, lengthBytes[:])
	if err != nil {
		return nil, err
	}

	length, _, _ := readi32(lengthBytes[:]) // ignore ok since we always have enough bytes to read a length
	if length < 0 {
		return nil, ErrInvalidLength
	}
	buffer := make([]byte, length)

	copy(buffer, lengthBytes[:])

	_, err = io.ReadFull(r, buffer[4:])
	if err != nil {
		return nil, err
	}

	if buffer[length-1] != 0x00 {
		return nil, ErrMissingNull
	}

	return buffer, nil
}

// Lookup searches the document, potentially recursively, for the given key. If there are multiple
// keys provided, this method will recurse down, as long as the top and intermediate nodes are
// either documents or arrays. If an error occurs or if the value doesn't exist, an empty Value is
// returned.
func (d Document) Lookup(key ...string) Value {
	val, _ := d.LookupErr(key...)
	return val
}

// LookupErr is the same as Lookup, except it returns an error in addition to an empty Value.
func (d Document) LookupErr(key ...string) (Value, error) {
	if len(key) < 1 {
		return Value{}, ErrEmptyKey
	}
	length, rem, ok := ReadLength(d)
	if !ok {
		return Value{}, NewInsufficientBytesError(d, rem)
	}

	length -= 4

	var elem Element
	for length > 1 {
		elem, rem, ok = ReadElement(rem)
		length -= int32(len(elem))
		if !ok {
			return Value{}, NewInsufficientBytesError(d, rem)
		}
		// We use `KeyBytes` rather than `Key` to avoid a needless string alloc.
		if string(elem.KeyBytes()) != key[0] {
			continue
		}
		if len(key) > 1 {
			tt := bsontype.Type(elem[0])
			switch tt {
			case bsontype.EmbeddedDocument:
				val, err := elem.Value().Document().LookupErr(key[1:]...)
				if err != nil {
					return Value{}, err
				}
				return val, nil
			case bsontype.Array:
				// Convert to Document to continue Lookup recursion.
				val, err := Document(elem.Value().Array()).LookupErr(key[1:]...)
				if err != nil {
					return Value{}, err
				}
				return val, nil
			default:
				return Value{}, InvalidDepthTraversalError{Key: elem.Key(), Type: tt}
			}
		}
		return elem.ValueErr()
	}
	return Value{}, ErrElementNotFound
}

// Index searches for and retrieves the element at the given index. This method will panic if
// the document is invalid or if the index is out of bounds.
func (d Document) Index(index uint) Element {
	elem, err := d.IndexErr(index)
	if err != nil {
		panic(err)
	}
	return elem
}

// IndexErr searches for and retrieves the element at the given index.
func (d Document) IndexErr(index uint) (Element, error) {
	return indexErr(d, index)
}

func indexErr(b []byte, index uint) (Element, error) {
	length, rem, ok := ReadLength(b)
	if !ok {
		return nil, NewInsufficientBytesError(b, rem)
	}

	length -= 4

	var current uint
	var elem Element
	for length > 1 {
		elem, rem, ok = ReadElement(rem)
		length -= int32(len(elem))
		if !ok {
			return nil, NewInsufficientBytesError(b, rem)
		}
		if current != index {
			current++
			continue
		}
		return elem, nil
	}
	return nil, ErrOutOfBounds
}

// DebugString outputs a human readable version of Document. It will attempt to stringify the
// valid components of the document even if the entire document is not valid.
func (d Document) DebugString() string {
	if len(d) < 5 {
		return "<malformed>"
	}
	var buf bytes.Buffer
	buf.WriteString("Document")
	length, rem, _ := ReadLength(d) // We know we have enough bytes to read the length
	buf.WriteByte('(')
	buf.WriteString(strconv.Itoa(int(length)))
	length -= 4
	buf.WriteString("){")
	var elem Element
	var ok bool
	for length > 1 {
		elem, rem, ok = ReadElement(rem)
		length -= int32(len(elem))
		if !ok {
			buf.WriteString(fmt.Sprintf("<malformed (%d)>", length))
			break
		}
		fmt.Fprintf(&buf, "%s ", elem.DebugString())
	}
	buf.WriteByte('}')

	return buf.String()
}

// String outputs an ExtendedJSON version of Document. If the document is not valid, this method
// returns an empty string.
func (d Document) String() string {
	if len(d) < 5 {
		return ""
	}
	var buf bytes.Buffer
	buf.WriteByte('{')

	length, rem, _ := ReadLength(d) // We know we have enough bytes to read the length

	length -= 4

	var elem Element
	var ok bool
	first := true
	for length > 1 {
		if !first {
			buf.WriteByte(',')
		}
		elem, rem, ok = ReadElement(rem)
		length -= int32(len(elem))
		if !ok {
			return ""
		}
		fmt.Fprintf(&buf, "%s", elem.String())
		first = false
	}
	buf.WriteByte('}')

	return buf.String()
}

// Elements returns this document as a slice of elements. The returned slice will contain valid
// elements. If the document is not valid, the elements up to the invalid point will be returned
// along with an error.
func (d Document) Elements() ([]Element, error) {
	length, rem, ok := ReadLength(d)
	if !ok {
		return nil, NewInsufficientBytesError(d, rem)
	}

	length -= 4

	var elem Element
	var elems []Element
	for length > 1 {
		elem, rem, ok = ReadElement(rem)
		length -= int32(len(elem))
		if !ok {
			return elems, NewInsufficientBytesError(d, rem)
		}
		if err := elem.Validate(); err != nil {
			return elems, err
		}
		elems = append(elems, elem)
	}
	return elems, nil
}

// Values returns this document as a slice of values. The returned slice will contain valid values.
// If the document is not valid, the values up to the invalid point will be returned along with an
// error.
func (d Document) Values() ([]Value, error) {
	return values(d)
}

func values(b []byte) ([]Value, error) {
	length, rem, ok := ReadLength(b)
	if !ok {
		return nil, NewInsufficientBytesError(b, rem)
	}

	length -= 4

	var elem Element
	var vals []Value
	for length > 1 {
		elem, rem, ok = ReadElement(rem)
		length -= int32(len(elem))
		if !ok {
			return vals, NewInsufficientBytesError(b, rem)
		}
		if err := elem.Value().Validate(); err != nil {
			return vals, err
		}
		vals = append(vals, elem.Value())
	}
	return vals, nil
}

// Validate validates the document and ensures the elements contained within are valid.
func (d Document) Validate() error {
	length, rem, ok := ReadLength(d)
	if !ok {
		return NewInsufficientBytesError(d, rem)
	}
	if int(length) > len(d) {
		return NewDocumentLengthError(int(length), len(d))
	}
	if d[length-1] != 0x00 {
		return ErrMissingNull
	}

	length -= 4
	var elem Element

	for length > 1 {
		elem, rem, ok = ReadElement(rem)
		length -= int32(len(elem))
		if !ok {
			return NewInsufficientBytesError(d, rem)
		}
		err := elem.Validate()
		if err != nil {
			return err
		}
	}

	if len(rem) < 1 || rem[0] != 0x00 {
		return ErrMissingNull
	}
	return nil
}


text:
class Augeas < Formula
  desc "Configuration editing tool and API"
  homepage "http://augeas.net"
  url "http://download.augeas.net/augeas-1.3.0.tar.gz"
  sha1 "052694bc84e3b8246dd32808b0e0e8c41c3de40b"

  bottle do
    sha1 "374c491053aff309ba2ae417f3bb6e888a4fbae9" => :yosemite
    sha1 "21e1bb5ec9d1bf623e61cf6ab1179a1d09cd9060" => :mavericks
    sha1 "3b3c437736fb3e4edb5c60a73f0097e91703dd1f" => :mountain_lion
  end

  head do
    url "https://github.com/hercules-team/augeas.git"

    depends_on "autoconf" => :build
    depends_on "automake" => :build
    depends_on "libtool" => :build
    depends_on "bison" => :build
  end

  depends_on "pkg-config" => :build
  depends_on "libxml2"
  depends_on "readline"

  def install
    args = %W[--disable-debug --disable-dependency-tracking --prefix=#{prefix}]

    if build.head?
      system "./autogen.sh", *args
    else
      system "./configure", *args
    end

    # libfa example program doesn't compile cleanly on OSX, so skip it
    inreplace "Makefile" do |s|
      s.change_make_var! "SUBDIRS", "gnulib/lib src gnulib/tests tests man doc"
    end

    system "make", "install"
  end

  def caveats; <<-EOS.undent
    Lenses have been installed to:
      #{HOMEBREW_PREFIX}/share/augeas/lenses/dist
    EOS
  end
end


text:
package com.easytoolsoft.easyreport.support.mapping;

import java.lang.reflect.Method;

import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.servlet.mvc.condition.RequestCondition;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

/**
 * 自定义RequestMappingHandlerMapping,实现url api版本兼容
 *
 * @author Tom Deng
 * @date 2017-03-25
 */
public class CustomRequestMappingHandlerMapping extends RequestMappingHandlerMapping {

    @Override
    protected RequestCondition<ApiVesrsionCondition> getCustomTypeCondition(Class<?> handlerType) {
        ApiVersion apiVersion = AnnotationUtils.findAnnotation(handlerType, ApiVersion.class);
        return createCondition(apiVersion);
    }

    @Override
    protected RequestCondition<ApiVesrsionCondition> getCustomMethodCondition(Method method) {
        ApiVersion apiVersion = AnnotationUtils.findAnnotation(method, ApiVersion.class);
        return createCondition(apiVersion);
    }

    private RequestCondition<ApiVesrsionCondition> createCondition(ApiVersion apiVersion) {
        return apiVersion == null ? null : new ApiVesrsionCondition(apiVersion.value());
    }
}


text:
<!DOCTYPE html>

<TITLE>Manpage of P11\-KIT</TITLE>
<meta charset="utf-8">
<link rel="stylesheet" href="/css/main.css" type="text/css">

linux manpages

{"type":"documentation"}

P11\-KIT

Section: System Commands (8)
Updated:
Index
Return to Main Contents

NAME

p11-kit - Tool for operating on configured PKCS#11 modules

SYNOPSIS

p11-kit list-modules

p11-kit extract --filter=<what> --format=<type> /path/to/destination
<TT>        </TT>

DESCRIPTION

p11-kit

is a command line tool that can be used to perform operations on PKCS#11 modules configured on the system.

See the various sub commands below. The following global options can be used:

-v, --verbose

Run in verbose mode with debug output.

-q, --quiet

Run in quiet mode without warning or failure messages.

LIST MODULES

List system configured PKCS#11 modules.

$ p11-kit list-modules

The modules, information about them and the tokens present in the PKCS#11 modules will be displayed.

EXTRACT

Extract certificates from configured PKCS#11 modules.

$ p11-kit extract --format=x509-directory --filter=ca-anchors /path/to/directory

You can specify the following options to control what to extract. The
--filter
and
--format
arguments should be specified. By default this command will not overwrite the destination file or directory.

--comment

Add identifying comments to PEM bundle output files before each certificate.

--filter=<what>

Specifies what certificates to extract. You can specify the following values:

ca-anchors

Certificate anchors (default)

trust-policy

Anchors and blacklist

blacklist

Blacklisted certificates

certificates

All certificates

pkcs11:object=xx

A PKCS#11 URI

If an output format is chosen that cannot support type what has been specified by the filter, a message will be printed.

None of the available formats support storage of blacklist entries that do not contain a full certificate. Thus any certificates blacklisted by their issuer and serial number alone, are not included in the extracted blacklist.

--format=<type>

The format of the destination file or directory. You can specify one of the following values:

x509-file

DER X.509 certificate file

x509-directory

directory of X.509 certificates

pem-bundle

File containing one or more certificate PEM blocks

pem-directory

Directory PEM files each containing one certifiacte

openssl-bundle

OpenSSL specific PEM bundle of certificates

openssl-directory

Directory of OpenSSL specific PEM files

java-cacerts

Java keystore 'cacerts' certificate bundle

--overwrite

Overwrite output file or directory.

--purpose=<usage>

Limit to certificates usable for the given purpose You can specify one of the following values:

server-auth

For authenticating servers

client-auth

For authenticating clients

email

For email protection

code-signing

For authenticated signed code

1.2.3.4.5...

An arbitrary purpose OID

EXTRACT TRUST

Extract standard trust information files.

$ p11-kit extract-trust

OpenSSL, GnuTLS and Java cannot currently read trust information directly from the trust policy module. This command extracts trust information such as certificate anchors for use by these libraries.

What this command does, and where it extracts the files is distribution or site specific. Packagers or administrators are expected customize this command.

BUGS

Please send bug reports to either the distribution bug tracker or the upstream bug tracker at
m[blue]https://bugs.freedesktop.org/enter_bug.cgi?product=p11-glue&component=p11-kitm[].

SEE ALSO

pkcs11.conf(5)

Further details available in the p11-kit online documentation at
m[blue]http://p11-glue.freedesktop.org/doc/p11-kit/m[].

Index

NAME

SYNOPSIS

DESCRIPTION

LIST MODULES

EXTRACT

EXTRACT TRUST

BUGS

SEE ALSO

This document was created by
man2html,
using the manual pages.

Time: 05:34:28 GMT, December 24, 2015


text:
// INCLUDE FILES
#include  <avkon.hrh>

#include <aknviewappui.h>
#include <akntabgrp.h>
#include <aknnavide.h>
#include <msvapi.h>

#include <arch.h>
#include "WayFinderConstants.h"
#include "RouteEnums.h"
#include "TimeOutNotify.h"
/* #include "PdaNavigatorProt.h" */
#include "GuiProt/GuiProtEnums.h"
#include  "WayFinderAppUi.h"

#include  "RsgInclude.h"
#include  "ContactsView.h"

#include  "ContactsContainer.h"
#include "memlog.h"
// ================= MEMBER FUNCTIONS =======================

// ---------------------------------------------------------
// CContactsView::ConstructL(const TRect& aRect)
// EPOC two-phased constructor
// ---------------------------------------------------------
//
void CContactsView::ConstructL()
{
   BaseConstructL( R_WAYFINDER_CONTACTS_VIEW );
}

// ---------------------------------------------------------
// CContactsView::~CContactsView()
// ?implementation_description
// ---------------------------------------------------------
//
CContactsView::~CContactsView()
{
   if ( iContainer ){
      AppUi()->RemoveFromViewStack( *this, iContainer );
   }

   LOGDEL(iContainer);
   delete iContainer;
}

// ---------------------------------------------------------
// TUid CContactsView::Id()
// ?implementation_description
// ---------------------------------------------------------
//
TUid CContactsView::Id() const
{
   return KContactsViewId;
}

// ---------------------------------------------------------
// CContactsView::HandleCommandL(TInt aCommand)
// ?implementation_description
// ---------------------------------------------------------
//
void CContactsView::HandleCommandL(TInt aCommand)
{
   switch ( aCommand )
   {
   case EAknSoftkeyOk:
      {
         iEikonEnv->InfoMsg( _L("view2 ok") );
         break;
      }
   default:
      {
         AppUi()->HandleCommandL( aCommand );
         break;
      }
   }
}

// ---------------------------------------------------------
// CContactsView::HandleClientRectChange()
// ---------------------------------------------------------
//
void CContactsView::HandleClientRectChange()
{
   if ( iContainer ){
      iContainer->SetRect( ClientRect() );
   }
}

// ---------------------------------------------------------
// CContactsView::DynInitMenuPaneL()
// ---------------------------------------------------------
//
void CContactsView::DynInitMenuPaneL( TInt aResourceId, CEikMenuPane* aMenuPane )
{
   AppUi()->DynInitMenuPaneL( aResourceId, aMenuPane );
}

// ---------------------------------------------------------
// CContactsView::DoActivateL(...)
// ?implementation_description
// ---------------------------------------------------------
//
void CContactsView::DoActivateL( const TVwsViewId& aPrevViewId,
                               TUid aCustomMessageId,
                               const TDesC8& aCustomMessage)
{
   CViewBase::DoActivateL(aPrevViewId, aCustomMessageId, aCustomMessage);
   if ( !iContainer ){
      iContainer = new (ELeave) CContactsContainer(iLog);
      LOGNEW(iContainer, CContactsContainer);
      iContainer->SetMopParent(this);
      iContainer->ConstructL( ClientRect() );
      AppUi()->AddToStackL( *this, iContainer );
   }
}

// ---------------------------------------------------------
// CContactsView::HandleCommandL(TInt aCommand)
// ?implementation_description
// ---------------------------------------------------------
//
void CContactsView::DoDeactivate()
{
   if ( iContainer ){
      AppUi()->RemoveFromViewStack( *this, iContainer );
   }

   LOGDEL(iContainer);
   delete iContainer;
   iContainer = NULL;
}

// End of File


text:
package com.vladsch.MissingInActions.actions.character;

import com.vladsch.MissingInActions.actions.DumbAwareTextComponentEditorAction;
import com.vladsch.MissingInActions.actions.LineSelectionAware;

public class DeleteToWordEndNotEolInDifferentHumpsModeAction extends DumbAwareTextComponentEditorAction implements LineSelectionAware {
    public DeleteToWordEndNotEolInDifferentHumpsModeAction() {
        super(new DeleteToWordEndNotEolActionHandler(true));
    }
}


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/datastore/v1/query.proto

package com.google.datastore.v1;

public interface PropertyOrderOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.datastore.v1.PropertyOrder)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * The property to order by.
   *

   *
   * .google.datastore.v1.PropertyReference property = 1;
   *
   * @return Whether the property field is set.
   */
  boolean hasProperty();
  /**
   *
   *
   *

   * The property to order by.
   *

   *
   * .google.datastore.v1.PropertyReference property = 1;
   *
   * @return The property.
   */
  com.google.datastore.v1.PropertyReference getProperty();
  /**
   *
   *
   *

   * The property to order by.
   *

   *
   * .google.datastore.v1.PropertyReference property = 1;
   */
  com.google.datastore.v1.PropertyReferenceOrBuilder getPropertyOrBuilder();

  /**
   *
   *
   *

   * The direction to order by. Defaults to `ASCENDING`.
   *

   *
   * .google.datastore.v1.PropertyOrder.Direction direction = 2;
   *
   * @return The enum numeric value on the wire for direction.
   */
  int getDirectionValue();
  /**
   *
   *
   *

   * The direction to order by. Defaults to `ASCENDING`.
   *

   *
   * .google.datastore.v1.PropertyOrder.Direction direction = 2;
   *
   * @return The direction.
   */
  com.google.datastore.v1.PropertyOrder.Direction getDirection();
}


text:
<!DOCTYPE html>
<html>
  <head>
    <title>Merge Chart</title>
  </head>
  <body>
    <canvas width="600" height="600"></canvas>
    <script src="chart.js"></script>
    <script charset="utf-8">
      var data = [
        {
          value: 100,
          color: '#46BFBD',
          highlight: '#5AD3D1',
          label: "People who understand merge conflicts"
        },
        {
          value: 50,
          color:'#F7464A',
          highlight: '#FF5A5E',
          label: "People who don't understand merge conflicts"
        },
        {
          value: 300,
          color: '#FDB45C',
          highlight: '#FFC870',
          label: "People who think they understand merge conflicts"
        }
      ];

      var options = { segmentStrokeColor: '#000', segmentStrokeWidth: 4 };

      document.addEventListener('DOMContentLoaded', function() {
        var canavs = document.getElementsByTagName('canvas')[0];
        var ctx = canavs.getContext('2d');
        var chart = new Chart(ctx).Pie(data, options);
      });
    </script>
  </body>
</html>


text:
import React, { PropTypes } from 'react';

import compose from 'recompose/compose';
import withHandlers from 'recompose/withHandlers';

import { StreamSourceWebcam, StreamSourceScreen } from 'vclub/constants/streamSources';

import SvgIcon from 'vclub/components/icons/SvgIcon';

import styles from './SourceSelect.css';

import AudioIcon from './ic_audiotrack_black_24px.svg';
import ScreenIcon from './ic_desktop_windows_black_24px.svg';
import MovieIcon from './ic_movie_black_24px.svg';
import CameraIcon from './ic_videocam_black_24px.svg';
import YoutubeIcon from './youtube.svg';

const enhance = compose(
  withHandlers({
    onWebcamSelected: (props) => () => {
      props.onSelected(StreamSourceWebcam);
    },
    onScreenSelected: (props) => () => {
      props.onSelected(StreamSourceScreen);
    },
    onYoutubeSelected: (/* props */) => () => {
    },
    onVideoSelected: (/* props */) => () => {
    },
    onAudioSelected: (/* props */) => () => {
    },
  })
);

function SourceSelect(props) {
  const {
    features,
    onWebcamSelected, onScreenSelected, onYoutubeSelected, onVideoSelected, onAudioSelected,
  } = props;

  return (

        <button className={styles.button} onClick={onWebcamSelected}>
          <SvgIcon className={styles.icon} glyph={CameraIcon} size={100} />
          Веб-камера
        </button>
        <button
          className={features.screenCapture ? styles.button : styles.buttonDisabled}
          onClick={onScreenSelected}
        >
          <SvgIcon className={styles.icon} glyph={ScreenIcon} size={100} />
          Экран
        </button>

        <button className={styles.buttonDisabled} onClick={onYoutubeSelected} disabled>
          <SvgIcon className={styles.icon} glyph={YoutubeIcon} size={100} />
          YouTube
        </button>
        <button className={styles.buttonDisabled} onClick={onVideoSelected} disabled>
          <SvgIcon className={styles.icon} glyph={MovieIcon} size={100} />
          Видео
        </button>
        <button className={styles.buttonDisabled} onClick={onAudioSelected} disabled>
          <SvgIcon className={styles.icon} glyph={AudioIcon} size={100} />
          Аудио
        </button>

  );
}

SourceSelect.propTypes = {
  features: PropTypes.object.isRequired,
  onWebcamSelected: PropTypes.func.isRequired,
  onScreenSelected: PropTypes.func.isRequired,
  onYoutubeSelected: PropTypes.func.isRequired,
  onVideoSelected: PropTypes.func.isRequired,
  onAudioSelected: PropTypes.func.isRequired,
};

export default enhance(SourceSelect);


text:
import collectd
import write_common

################################################################################
# Globals
################################################################################

#
# Name of this plugin for logging
#
plugin_name = 'write_log_json'

#
# Default configuration values
#
config = {
    'TypesDB': ['/usr/share/collectd/types.db']
}

#
# Parsed types.db values
#
types = {}

################################################################################
# Handlers
################################################################################

def handle_config(given_config):
    global config
    config = write_common.merge_configs(config, given_config, plugin_name)

    collectd.info('%s: Configured: %s' % (plugin_name, config))

def handle_init():
    global types
    types = write_common.parse_types_db(config['TypesDB'], plugin_name)

    # If we made it this far, go ahead and register the write plugin
    collectd.register_write(handle_write)
    collectd.info(
        '%s: Initialized and registered write handler.' % plugin_name)

def handle_write(vl):
    collectd.info(write_common.value_to_json(vl, types))

################################################################################
# Register handlers
################################################################################

# register_config(...)
# register_config(callback[, data][, name]) -> identifier
#
# Register a callback function for config file entries.
#
#     'callback' is a callable object that will be called for every config block
#     'data' is an optional object that will be passed back to the callback
#         function every time it is called.
#     'name' is an optional identifier for this callback. The default name
#         is 'python.<module>'.
#         Every callback needs a unique identifier, so if you want to
#         register this callback multiple time from the same module you need
#         to specify a name here.
#     'identifier' is the full identifier assigned to this callback.
#
#     The callback function will be called with one or two parameters:
#     config: A Config object.
#     data: The optional data parameter passed to the register function.
#         If the parameter was omitted it will be omitted here, too.

collectd.register_config(handle_config)

# register_init(...)
# register_init(callback[, data][, name]) -> identifier
#
#     Register a callback function that will be executed once after the config.
#     file has been read, all plugins heve been loaded and the collectd has
#     forked into the background.
#
#     'callback' is a callable object that will be executed.
#     'data' is an optional object that will be passed back to the callback
#         function when it is called.
#     'name' is an optional identifier for this callback. The default name
#         is 'python.<module>'.
#         Every callback needs a unique identifier, so if you want to
#         register this callback multiple time from the same module you need
#         to specify a name here.
#     'identifier' is the full identifier assigned to this callback.
#
#     The callback function will be called without parameters, except for
#     data if it was supplied.

collectd.register_init(handle_init)

# register_write(...)
# register_write(callback[, data][, name]) -> identifier
#
#     Register a callback function to receive values dispatched by other plugins
#
#     'callback' is a callable object that will be called every time a value
#         is dispatched.
#     'data' is an optional object that will be passed back to the callback
#         function every time it is called.
#     'name' is an optional identifier for this callback. The default name
#         is 'python.<module>'.
#         Every callback needs a unique identifier, so if you want to
#         register this callback multiple time from the same module you need
#         to specify a name here.
#     'identifier' is the full identifier assigned to this callback.
#
#     The callback function will be called with one or two parameters:
#     values: A Values object which is a copy of the dispatched values.
#     data: The optional data parameter passed to the register function.
#         If the parameter was omitted it will be omitted here, too.

# collectd.register_write(handle_write) # Registered as part of handle_init


text:
@implementation MKTPointerArgumentGetter

- (instancetype)initWithSuccessor:(MKTArgumentGetter *)successor
{
    self = [super initWithType:@encode(void *) successor:successor];
    return self;
}

- (id)getArgumentAtIndex:(NSInteger)idx ofType:(char const *)type onInvocation:(NSInvocation *)invocation
{
    void *arg;
    [invocation getArgument:&arg atIndex:idx];
    return [NSValue valueWithPointer:arg];
}

@end