text:
// Copyright (c) 2016, Huang-Ming Huang,  Object Computing, Inc.
// All rights reserved.
//
// This file is part of mFAST.
// See the file license.txt for licensing information.
#include "templates_builder.h"
#include "../boolean_ref.h"
#include "view_info_builder.h"
#include "../exceptions.h"

using namespace tinyxml2;

//////////////////////////////////////////////////////////////////////////////////////
namespace mfast {
namespace xml_parser {

static const uint32_field_instruction
    length_instruction_prototype(operator_none, presence_mandatory, 0,
                                 "__length__", "", nullptr,
                                 int_value_storage<uint32_t>());

templates_builder::templates_builder(dynamic_templates_description *definition,
                                     const char *cpp_ns,
                                     template_registry *registry)
    : field_builder_base(registry->impl_, &this->member),
      definition_(definition), cpp_ns_(string_dup(cpp_ns, this->alloc())),
      template_instruction_prototype_(0, nullptr, "", "", "",
                                      instructions_view_t(nullptr, 0), 0,
                                      nullptr, nullptr, cpp_ns_),
      group_field_instruction_prototype_(presence_mandatory, 0, nullptr, "", "",
                                         instructions_view_t(nullptr, 0), "",
                                         "", cpp_ns_),
      sequence_field_instruction_prototype_(
          presence_mandatory, 0, nullptr, "", "",
          instructions_view_t(nullptr, 0), nullptr, nullptr,
          &length_instruction_prototype, "", "", cpp_ns_),
      enum_field_instruction_prototype_(operator_none, presence_mandatory, 0,
                                        nullptr, "", nullptr, 0, nullptr,
                                        nullptr, 0, nullptr, cpp_ns_) {
  static const int32_field_instruction int32_field_instruction_prototype(
      operator_none, presence_mandatory, 0, nullptr, "", nullptr,
      int_value_storage<int32_t>());
  this->member["int32"] = &int32_field_instruction_prototype;

  static const uint32_field_instruction uint32_field_instruction_prototype(
      operator_none, presence_mandatory, 0, nullptr, "", nullptr,
      int_value_storage<uint32_t>());
  this->member["uInt32"] = &uint32_field_instruction_prototype;

  static const int64_field_instruction int64_field_instruction_prototype(
      operator_none, presence_mandatory, 0, nullptr, "", nullptr,
      int_value_storage<int64_t>());
  this->member["int64"] = &int64_field_instruction_prototype;

  static const uint64_field_instruction uint64_field_instruction_prototype(
      operator_none, presence_mandatory, 0, nullptr, "", nullptr,
      int_value_storage<uint64_t>());
  this->member["uInt64"] = &uint64_field_instruction_prototype;

  static const decimal_field_instruction decimal_field_instruction_prototype(
      operator_none, presence_mandatory, 0, nullptr, "", nullptr,
      decimal_value_storage());
  this->member["decimal"] = &decimal_field_instruction_prototype;

  static const ascii_field_instruction ascii_field_instruction_prototype(
      operator_none, presence_mandatory, 0, nullptr, "", nullptr,
      string_value_storage());
  this->member["string"] = &ascii_field_instruction_prototype;

  static const byte_vector_field_instruction
      byte_vector_field_instruction_prototype(
          operator_none, presence_mandatory, 0, nullptr, "", nullptr,
          string_value_storage(), 0, "", "");
  this->member["byteVector"] = &byte_vector_field_instruction_prototype;

  static const int32_vector_field_instruction
      int32_vector_field_instruction_prototype(presence_mandatory, 0, nullptr,
                                               "");
  this->member["int32Vector"] = &int32_vector_field_instruction_prototype;

  static const uint32_vector_field_instruction
      uint32_vector_field_instruction_prototype(presence_mandatory, 0, nullptr,
                                                "");
  this->member["uInt32Vector"] = &uint32_vector_field_instruction_prototype;

  static const int64_vector_field_instruction
      int64_vector_field_instruction_prototype(presence_mandatory, 0, nullptr,
                                               "");
  this->member["int64Vector"] = &int64_vector_field_instruction_prototype;

  static const uint64_vector_field_instruction
      uint64_vector_field_instruction_prototype(presence_mandatory, 0, nullptr,
                                                "");
  this->member["uInt64Vector"] = &uint64_vector_field_instruction_prototype;

  this->member["group"] = &group_field_instruction_prototype_;
  this->member["sequence"] = &sequence_field_instruction_prototype_;
  this->member["template"] = &template_instruction_prototype_;
  this->member["boolean"] = mfast::boolean::instruction();
  this->member["enum"] = &enum_field_instruction_prototype_;
}

bool templates_builder::VisitEnter(const XMLElement &element,
                                   const XMLAttribute *) {
  const char *element_name = element.Name();

  if (std::strcmp(element_name, "templates") == 0) {
    definition_->ns_ =
        string_dup(get_optional_attr(element, "ns", ""), alloc());

    resolved_ns_ =
        string_dup(get_optional_attr(element, "templateNs", ""), alloc());
    definition_->template_ns_ = resolved_ns_;
    definition_->dictionary_ =
        string_dup(get_optional_attr(element, "dictionary", ""), alloc());
    return true;
  } else if (strcmp(element_name, "define") == 0) {
    const char *name = get_optional_attr(element, "name", nullptr);
    const XMLElement *elem = element.FirstChildElement();
    if (name && elem) {
      field_builder builder(this, *elem, name);
      builder.build();
    }
  } else if (strcmp(element_name, "template") == 0) {
    field_builder builder(this, element);
    builder.build();
  } else if (strcmp(element_name, "view") == 0) {
    view_info_builder builder(alloc());
    const group_field_instruction *inst =
        dynamic_cast<const group_field_instruction *>(
            this->find_type(get_optional_attr(element, "ns", resolved_ns_),
                            get_optional_attr(element, "reference", "")));

    if (inst == nullptr)
      BOOST_THROW_EXCEPTION(fast_static_error("Invalid view specification"));
    definition_->view_infos_.push_back(builder.build(element, inst));
  }
  return false;
}

bool templates_builder::VisitExit(const XMLElement &element) {
  if (std::strcmp(element.Name(), "templates") == 0) {
    typedef const template_instruction *const_template_instruction_ptr_t;

    definition_->instructions_ = new (alloc())
        const_template_instruction_ptr_t[templates_.size()];
    std::copy(templates_.begin(), templates_.end(), definition_->instructions_);
    definition_->instructions_count_ = static_cast<uint32_t>(templates_.size());
  }
  return true;
}

std::size_t templates_builder::num_instructions() const {
  return local_types()->size();
}

void templates_builder::add_instruction(const field_instruction *inst) {
  member[inst->name()] = inst;

  if (inst->field_type() >= field_type_sequence) {
    definition_->defined_type_instructions_.push_back(inst);
    const char *ns = inst->ns();
    if (ns == nullptr || ns[0] == '\0')
      ns = resolved_ns_;
    registry()->add(ns, inst);
  }
}

void templates_builder::add_template(const char *ns,
                                     template_instruction *inst) {
  templates_.push_back(inst);
  registry()->add(ns, inst);
}

/////////////////////////////////////////////////////////////////////////////////
} /* coder */

template_registry::template_registry()
    : impl_(new xml_parser::template_registry_impl) {}

template_registry::~template_registry() { delete impl_; }

template_registry *template_registry::instance() {
  static template_registry inst;
  return &inst;
}

arena_allocator *template_registry::alloc() { return &(this->impl_->alloc_); }

dynamic_templates_description::dynamic_templates_description(
    const char *xml_content, const char *cpp_ns, template_registry *registry) {
  XMLDocument document;
  if (document.Parse(xml_content) == 0) {
    xml_parser::templates_builder builder(this, cpp_ns, registry);
    document.Accept(&builder);
  } else {
    BOOST_THROW_EXCEPTION(std::runtime_error("XML parse error"));
  }
}

const std::deque<const field_instruction *> &
dynamic_templates_description::defined_type_instructions() const {
  return defined_type_instructions_;
}

} /* mfast */


text:
module.exports = {

  title: 'Create lunches table',

  up: function(data){

    return data.schema.createTable('lunches', function(table){
      table.increments('id').primary();
      table.integer('user_id');
      table.string('name');
      table.integer('restaurant_id');
      table.timestamps();
    }).then(function(){
      console.log('created lunches'.green);
    });

  },

  down: function(data){

    return data.schema.dropTable('lunches')
      .then(function(){
        console.log('dropped lunches'.red);
      })
    ;

  }
};

redpajama_set_name: RedPajamaGithub


text:
export enum ContextGLClearMask
{
	COLOR = 1,
	DEPTH = 2,
	STENCIL = 4,
	ALL = ContextGLClearMask.COLOR | ContextGLClearMask.DEPTH | ContextGLClearMask.STENCIL
}


text:
package org.elasticsearch.env;

import org.apache.lucene.store.LockObtainFailedException;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.LuceneTestCase;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.common.io.PathUtils;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.concurrent.AbstractRunnable;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.test.ESTestCase;
import org.junit.Test;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_SHARDS;
import static org.elasticsearch.common.settings.Settings.settingsBuilder;
import static org.hamcrest.CoreMatchers.equalTo;

@LuceneTestCase.SuppressFileSystems("ExtrasFS") // TODO: fix test to allow extras
public class NodeEnvironmentTests extends ESTestCase {

    private final Settings idxSettings = Settings.builder().put(SETTING_NUMBER_OF_SHARDS, 1).build();

    @Test
    public void testNodeLockSingleEnvironment() throws IOException {
        NodeEnvironment env = newNodeEnvironment(Settings.builder()
                .put("node.max_local_storage_nodes", 1).build());
        Settings settings = env.getSettings();
        String[] dataPaths = env.getSettings().getAsArray("path.data");

        try {
            new NodeEnvironment(settings, new Environment(settings));
            fail("env is already locked");
        } catch (IllegalStateException ex) {

        }
        env.close();

        // now can recreate and lock it
        env = new NodeEnvironment(settings, new Environment(settings));
        assertEquals(env.nodeDataPaths().length, dataPaths.length);

        for (int i = 0; i < dataPaths.length; i++) {
            assertTrue(env.nodeDataPaths()[i].startsWith(PathUtils.get(dataPaths[i])));
        }
        env.close();
        assertTrue("LockedShards: " + env.lockedShards(), env.lockedShards().isEmpty());

    }

    @Test
    public void testNodeLockMultipleEnvironment() throws IOException {
        final NodeEnvironment first = newNodeEnvironment();
        String[] dataPaths = first.getSettings().getAsArray("path.data");
        NodeEnvironment second = new NodeEnvironment(first.getSettings(), new Environment(first.getSettings()));
        assertEquals(first.nodeDataPaths().length, dataPaths.length);
        assertEquals(second.nodeDataPaths().length, dataPaths.length);
        for (int i = 0; i < dataPaths.length; i++) {
            assertEquals(first.nodeDataPaths()[i].getParent(), second.nodeDataPaths()[i].getParent());
        }
        IOUtils.close(first, second);
    }

    @Test
    public void testShardLock() throws IOException {
        final NodeEnvironment env = newNodeEnvironment();

        ShardLock fooLock = env.shardLock(new ShardId("foo", 0));
        assertEquals(new ShardId("foo", 0), fooLock.getShardId());

        try {
            env.shardLock(new ShardId("foo", 0));
            fail("shard is locked");
        } catch (LockObtainFailedException ex) {
            // expected
        }
        for (Path path : env.indexPaths(new Index("foo"))) {
            Files.createDirectories(path.resolve("0"));
            Files.createDirectories(path.resolve("1"));
        }
        Settings settings = settingsBuilder().put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, randomIntBetween(1, 10)).build();
        try {
            env.lockAllForIndex(new Index("foo"), settings, randomIntBetween(0, 10));
            fail("shard 0 is locked");
        } catch (LockObtainFailedException ex) {
            // expected
        }

        fooLock.close();
        // can lock again?
        env.shardLock(new ShardId("foo", 0)).close();

        List<ShardLock> locks = env.lockAllForIndex(new Index("foo"), settings, randomIntBetween(0, 10));
        try {
            env.shardLock(new ShardId("foo", 0));
            fail("shard is locked");
        } catch (LockObtainFailedException ex) {
            // expected
        }
        IOUtils.close(locks);
        assertTrue("LockedShards: " + env.lockedShards(), env.lockedShards().isEmpty());
        env.close();
    }

    @Test
    public void testGetAllIndices() throws Exception {
        final NodeEnvironment env = newNodeEnvironment();
        final int numIndices = randomIntBetween(1, 10);
        for (int i = 0; i < numIndices; i++) {
            for (Path path : env.indexPaths(new Index("foo" + i))) {
                Files.createDirectories(path);
            }
        }
        Set<String> indices = env.findAllIndices();
        assertEquals(indices.size(), numIndices);
        for (int i = 0; i < numIndices; i++) {
            assertTrue(indices.contains("foo" + i));
        }
        assertTrue("LockedShards: " + env.lockedShards(), env.lockedShards().isEmpty());
        env.close();
    }

    @Test
    public void testDeleteSafe() throws IOException, InterruptedException {
        final NodeEnvironment env = newNodeEnvironment();
        ShardLock fooLock = env.shardLock(new ShardId("foo", 0));
        assertEquals(new ShardId("foo", 0), fooLock.getShardId());

        for (Path path : env.indexPaths(new Index("foo"))) {
            Files.createDirectories(path.resolve("0"));
            Files.createDirectories(path.resolve("1"));
        }

        try {
            env.deleteShardDirectorySafe(new ShardId("foo", 0), idxSettings);
            fail("shard is locked");
        } catch (LockObtainFailedException ex) {
            // expected
        }

        for (Path path : env.indexPaths(new Index("foo"))) {
            assertTrue(Files.exists(path.resolve("0")));
            assertTrue(Files.exists(path.resolve("1")));

        }

        env.deleteShardDirectorySafe(new ShardId("foo", 1), idxSettings);

        for (Path path : env.indexPaths(new Index("foo"))) {
            assertTrue(Files.exists(path.resolve("0")));
            assertFalse(Files.exists(path.resolve("1")));
        }

        try {
            env.deleteIndexDirectorySafe(new Index("foo"), randomIntBetween(0, 10), idxSettings);
            fail("shard is locked");
        } catch (LockObtainFailedException ex) {
            // expected
        }
        fooLock.close();

        for (Path path : env.indexPaths(new Index("foo"))) {
            assertTrue(Files.exists(path));
        }

        final AtomicReference<Throwable> threadException = new AtomicReference<>();
        final CountDownLatch latch = new CountDownLatch(1);
        final CountDownLatch blockLatch = new CountDownLatch(1);
        final CountDownLatch start = new CountDownLatch(1);
        if (randomBoolean()) {
            Thread t = new Thread(new AbstractRunnable() {
                @Override
                public void onFailure(Throwable t) {
                    logger.error("unexpected error", t);
                    threadException.set(t);
                    latch.countDown();
                    blockLatch.countDown();
                }

                @Override
                protected void doRun() throws Exception {
                    start.await();
                    try (ShardLock _ = env.shardLock(new ShardId("foo", 0))) {
                        blockLatch.countDown();
                        Thread.sleep(randomIntBetween(1, 10));
                    }
                    latch.countDown();
                }
            });
            t.start();
        } else {
            latch.countDown();
            blockLatch.countDown();
        }
        start.countDown();
        blockLatch.await();

        env.deleteIndexDirectorySafe(new Index("foo"), 5000, idxSettings);

        assertNull(threadException.get());

        for (Path path : env.indexPaths(new Index("foo"))) {
            assertFalse(Files.exists(path));
        }
        latch.await();
        assertTrue("LockedShards: " + env.lockedShards(), env.lockedShards().isEmpty());
        env.close();
    }

    @Test
    public void testStressShardLock() throws IOException, InterruptedException {
        class Int {
            int value = 0;
        }
        final NodeEnvironment env = newNodeEnvironment();
        final int shards = randomIntBetween(2, 10);
        final Int[] counts = new Int[shards];
        final AtomicInteger[] countsAtomic = new AtomicInteger[shards];
        final AtomicInteger[] flipFlop = new AtomicInteger[shards];

        for (int i = 0; i < counts.length; i++) {
            counts[i] = new Int();
            countsAtomic[i] = new AtomicInteger();
            flipFlop[i] = new AtomicInteger();
        }

        Thread[] threads = new Thread[randomIntBetween(2,5)];
        final CountDownLatch latch = new CountDownLatch(1);
        final int iters = scaledRandomIntBetween(10000, 100000);
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread() {
                @Override
                public void run() {
                    try {
                        latch.await();
                    } catch (InterruptedException e) {
                        fail(e.getMessage());
                    }
                    for (int i = 0; i < iters; i++) {
                        int shard = randomIntBetween(0, counts.length-1);
                        try {
                            try (ShardLock _ = env.shardLock(new ShardId("foo", shard), scaledRandomIntBetween(0, 10))) {
                                counts[shard].value++;
                                countsAtomic[shard].incrementAndGet();
                                assertEquals(flipFlop[shard].incrementAndGet(), 1);
                                assertEquals(flipFlop[shard].decrementAndGet(), 0);
                            }
                        } catch (LockObtainFailedException ex) {
                            // ok
                        } catch (IOException ex) {
                            fail(ex.toString());
                        }
                    }
                }
            };
            threads[i].start();
        }
        latch.countDown(); // fire the threads up
        for (int i = 0; i < threads.length; i++) {
            threads[i].join();
        }

        assertTrue("LockedShards: " + env.lockedShards(), env.lockedShards().isEmpty());
        for (int i = 0; i < counts.length; i++) {
            assertTrue(counts[i].value > 0);
            assertEquals(flipFlop[i].get(), 0);
            assertEquals(counts[i].value, countsAtomic[i].get());
        }
        env.close();
    }

    @Test
    public void testCustomDataPaths() throws Exception {
        String[] dataPaths = tmpPaths();
        NodeEnvironment env = newNodeEnvironment(dataPaths, Settings.EMPTY);

        Settings s1 = Settings.builder().put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1).build();
        Settings s2 = Settings.builder().put(IndexMetaData.SETTING_DATA_PATH, "/tmp/foo").build();
        ShardId sid = new ShardId("myindex", 0);
        Index i = new Index("myindex");

        assertFalse("no settings should mean no custom data path", NodeEnvironment.hasCustomDataPath(s1));
        assertTrue("settings with path_data should have a custom data path", NodeEnvironment.hasCustomDataPath(s2));

        assertThat(env.availableShardPaths(sid), equalTo(env.availableShardPaths(sid)));
        assertFalse(NodeEnvironment.hasCustomDataPath(s1));
        assertThat(env.resolveCustomLocation(s2, sid), equalTo(PathUtils.get("/tmp/foo/0/myindex/0")));
        assertTrue(NodeEnvironment.hasCustomDataPath(s2));

        assertThat("shard paths with a custom data_path should contain only regular paths",
                env.availableShardPaths(sid),
                equalTo(stringsToPaths(dataPaths, "elasticsearch/nodes/0/indices/myindex/0")));

        assertThat("index paths uses the regular template",
                env.indexPaths(i), equalTo(stringsToPaths(dataPaths, "elasticsearch/nodes/0/indices/myindex")));

        env.close();
        NodeEnvironment env2 = newNodeEnvironment(dataPaths,
                Settings.builder().put(NodeEnvironment.ADD_NODE_ID_TO_CUSTOM_PATH, false).build());

        assertThat(env2.availableShardPaths(sid), equalTo(env2.availableShardPaths(sid)));
        assertThat(env2.resolveCustomLocation(s2, sid), equalTo(PathUtils.get("/tmp/foo/myindex/0")));

        assertThat("shard paths with a custom data_path should contain only regular paths",
                env2.availableShardPaths(sid),
                equalTo(stringsToPaths(dataPaths, "elasticsearch/nodes/0/indices/myindex/0")));

        assertThat("index paths uses the regular template",
                env2.indexPaths(i), equalTo(stringsToPaths(dataPaths, "elasticsearch/nodes/0/indices/myindex")));

        env2.close();
    }

    /** Converts an array of Strings to an array of Paths, adding an additional child if specified */
    private Path[] stringsToPaths(String[] strings, String additional) {
        Path[] locations = new Path[strings.length];
        for (int i = 0; i < strings.length; i++) {
            locations[i] = PathUtils.get(strings[i], additional);
        }
        return locations;
    }

    @Override
    public String[] tmpPaths() {
        final int numPaths = randomIntBetween(1, 3);
        final String[] absPaths = new String[numPaths];
        for (int i = 0; i < numPaths; i++) {
            absPaths[i] = createTempDir().toAbsolutePath().toString();
        }
        return absPaths;
    }

    @Override
    public NodeEnvironment newNodeEnvironment() throws IOException {
        return newNodeEnvironment(Settings.EMPTY);
    }

    @Override
    public NodeEnvironment newNodeEnvironment(Settings settings) throws IOException {
        Settings build = Settings.builder()
                .put(settings)
                .put("path.home", createTempDir().toAbsolutePath().toString())
                .put(NodeEnvironment.SETTING_CUSTOM_DATA_PATH_ENABLED, true)
                .putArray("path.data", tmpPaths()).build();
        return new NodeEnvironment(build, new Environment(build));
    }

    public NodeEnvironment newNodeEnvironment(String[] dataPaths, Settings settings) throws IOException {
        Settings build = Settings.builder()
                .put(settings)
                .put("path.home", createTempDir().toAbsolutePath().toString())
                .put(NodeEnvironment.SETTING_CUSTOM_DATA_PATH_ENABLED, true)
                .putArray("path.data", dataPaths).build();
        return new NodeEnvironment(build, new Environment(build));
    }
}


text:
package cni

import (
	"fmt"
	"strings"
	"sync"

	cnilibrary "github.com/containernetworking/cni/libcni"
	"github.com/containernetworking/cni/pkg/types/current"
	"github.com/pkg/errors"
)

type CNI interface {
	// Setup setup the network for the namespace
	Setup(id string, path string, opts ...NamespaceOpts) (*CNIResult, error)
	// Remove tears down the network of the namespace.
	Remove(id string, path string, opts ...NamespaceOpts) error
	// Load loads the cni network config
	Load(opts ...CNIOpt) error
	// Status checks the status of the cni initialization
	Status() error
}

type libcni struct {
	config

	cniConfig    cnilibrary.CNI
	networkCount int // minimum network plugin configurations needed to initialize cni
	networks     []*Network
	sync.RWMutex
}

func defaultCNIConfig() *libcni {
	return &libcni{
		config: config{
			pluginDirs:    []string{DefaultCNIDir},
			pluginConfDir: DefaultNetDir,
			prefix:        DefaultPrefix,
		},
		cniConfig: &cnilibrary.CNIConfig{
			Path: []string{DefaultCNIDir},
		},
		networkCount: 1,
	}
}

func New(config ...CNIOpt) (CNI, error) {
	cni := defaultCNIConfig()
	var err error
	for _, c := range config {
		if err = c(cni); err != nil {
			return nil, err
		}
	}
	return cni, nil
}

func (c *libcni) Load(opts ...CNIOpt) error {
	var err error
	c.Lock()
	defer c.Unlock()
	// Reset the networks on a load operation to ensure
	// config happens on a clean slate
	c.reset()

	for _, o := range opts {
		if err = o(c); err != nil {
			return errors.Wrapf(ErrLoad, fmt.Sprintf("cni config load failed: %v", err))
		}
	}
	return nil
}

func (c *libcni) Status() error {
	c.RLock()
	defer c.RUnlock()
	return c.status()
}

// Setup setups the network in the namespace
func (c *libcni) Setup(id string, path string, opts ...NamespaceOpts) (*CNIResult, error) {
	c.RLock()
	defer c.RUnlock()
	if err := c.status(); err != nil {
		return nil, err
	}
	ns, err := newNamespace(id, path, opts...)
	if err != nil {
		return nil, err
	}
	var results []*current.Result
	for _, network := range c.networks {
		r, err := network.Attach(ns)
		if err != nil {
			return nil, err
		}
		results = append(results, r)
	}
	return c.GetCNIResultFromResults(results)
}

// Remove removes the network config from the namespace
func (c *libcni) Remove(id string, path string, opts ...NamespaceOpts) error {
	c.RLock()
	defer c.RUnlock()
	if err := c.status(); err != nil {
		return err
	}
	ns, err := newNamespace(id, path, opts...)
	if err != nil {
		return err
	}
	for _, network := range c.networks {
		if err := network.Remove(ns); err != nil {
			// Based on CNI spec v0.7.0, empty network namespace is allowed to
			// do best effort cleanup. However, it is not handled consistently
			// right now:
			// https://github.com/containernetworking/plugins/issues/210
			// TODO(random-liu): Remove the error handling when the issue is
			// fixed and the CNI spec v0.6.0 support is deprecated.
			if path == "" && strings.Contains(err.Error(), "no such file or directory") {
				continue
			}
			return err
		}
	}
	return nil
}

func (c *libcni) reset() {
	c.networks = nil
}

func (c *libcni) status() error {
	if len(c.networks) < c.networkCount {
		return ErrCNINotInitialized
	}
	return nil
}


text:
<!DOCTYPE html>

    <title>Caisse App</title>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="description" content="">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no" />

    <link rel='stylesheet' href='http://fonts.googleapis.com/css?family=Roboto:400,500,700,400italic'>
    <link rel="stylesheet" href="../../node_modules/angular-material/angular-material.css"/>
    <link rel="stylesheet" href="assets/app.css"/>

    <md-toolbar class="md-hue-2">

        <md-button ng-if="app.modules.length > 1" class="md-icon-button" aria-label="Menu" ng-click="app.toggleModulesList()">
          <md-icon md-svg-icon="menu" ></md-icon>
        </md-button>

          Qrea App
           > {{ app.moduleSelected.name }}

    </md-toolbar>

        <md-sidenav ng-if="app.modules.length > 1" ng-click="app.toggleModulesList()"
          md-is-locked-open="$mdMedia('gt-sm') && app.modules.length > 1" md-component-id="left" class="md-whiteframe-z2">
          <md-list>
            <md-list-item ng-repeat="it in app.modules">
                <md-button ng-click="ul.selectModule(it)" ng-class="{'selected' : it === app.moduleSelected }">
                  {{it.name}}
                </md-button>
            </md-list-item>
          </md-list>
        </md-sidenav>

        <md-content ng-view flex layout-padding>
        </md-content>


text:
const path = require('path');
const rootPath = process.cwd();
const context = path.join(rootPath, "src");
const outputPath = path.join(rootPath, 'dist');
const bannerPlugin = require(path.join(__dirname, 'plugins', 'banner.js'));

module.exports = {
  mode: 'development',
  context: context,
  entry: {
    dicomParser: './index.js'
  },
  target: 'web',
  output: {
    filename: '[name].js',
    library: {
      commonjs: "dicom-parser",
      amd: "dicom-parser",
      root: 'dicomParser'
    },
    libraryTarget: 'umd',
    globalObject: 'this',
    path: outputPath,
    umdNamedDefine: true
  },
  devtool: 'source-map',
  module: {
    rules: [{
      enforce: 'pre',
      test: /\.js$/,
      exclude: /(node_modules|test)/,
      loader: 'eslint-loader',
      options: {
        failOnError: false
      }
    }, {
      test: /\.js$/,
      exclude: /(node_modules)/,
      use: [{
        loader: 'babel-loader'
      }]
    }]
  },
  plugins: [
    bannerPlugin()
  ]
};


text:
package org.eclipse.rdf4j.sail.memory.model;

import org.eclipse.rdf4j.model.BNode;

/**
 * A MemoryStore-specific extension of BNodeImpl giving it node properties.
 */
public class MemBNode extends MemResource implements BNode {

	private static final long serialVersionUID = -887382892580321647L;

	/*------------*
	 * Attributes *
	 *------------*/

	/**
	 * The object that created this MemBNode.
	 */
	transient final private Object creator;

	/**
	 * The list of statements for which this MemBNode is the object.
	 */
	transient private final MemStatementList objectStatements = new MemStatementList();
	/**
	 * The blank node's identifier.
	 */
	private final String id;

	/*--------------*
	 * Constructors *
	 *--------------*/

	/**
	 * Creates a new MemBNode for a bnode ID.
	 *
	 * @param creator The object that is creating this MemBNode.
	 * @param id      bnode ID.
	 */
	public MemBNode(Object creator, String id) {
		this.id = id;
		this.creator = creator;
	}

	/*---------*
	 * Methods *
	 *---------*/

	@Override
	public Object getCreator() {
		return creator;
	}

	@Override
	public boolean hasStatements() {
		return !subjectStatements.isEmpty() || !objectStatements.isEmpty() || !contextStatements.isEmpty();
	}

	@Override
	public MemStatementList getObjectStatementList() {

		return objectStatements;

	}

	@Override
	public int getObjectStatementCount() {

		return objectStatements.size();

	}

	@Override
	public void addObjectStatement(MemStatement st) throws InterruptedException {

		objectStatements.add(st);
	}

	@Override
	public void removeObjectStatement(MemStatement st) throws InterruptedException {
		objectStatements.remove(st);

	}

	@Override
	public void cleanSnapshotsFromObjectStatements(int currentSnapshot) throws InterruptedException {
		objectStatements.cleanSnapshots(currentSnapshot);

	}

	@Override
	public boolean hasPredicateStatements() {
		return false;
	}

	@Override
	public boolean hasObjectStatements() {
		return !objectStatements.isEmpty();
	}

	@Override
	public String getID() {
		return id;
	}

	@Override
	public String stringValue() {
		return getID();
	}

	@Override
	public boolean equals(Object o) {
		return this == o || o instanceof BNode
				&& getID().equals(((BNode) o).getID());
	}

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

	@Override
	public String toString() {
		return "_:" + getID();
	}
}


text:
module Hint.Annotations (
    getModuleAnnotations,
    getValAnnotations
) where

import Control.Monad
import Data.Data
import Annotations
import Serialized

import Hint.Base
import HscTypes (hsc_mod_graph, ms_mod)
import qualified Hint.GHC as GHC

-- Get the annotations associated with a particular module.
getModuleAnnotations :: (Data a, MonadInterpreter m) => a -> String -> m [a]
getModuleAnnotations _ x = do
    mods <- liftM hsc_mod_graph $ runGhc GHC.getSession
    let x' = filter ((==) x . GHC.moduleNameString . GHC.moduleName . ms_mod) mods
    v <- mapM (anns . ModuleTarget . ms_mod) x'
    return $ concat v

-- Get the annotations associated with a particular function.
getValAnnotations :: (Data a, MonadInterpreter m) => a -> String -> m [a]
getValAnnotations _ x = do
    x' <- runGhc1 GHC.parseName x
    v <- mapM (anns . NamedTarget) x'
    return $ concat v

anns :: (MonadInterpreter m, Data a) => AnnTarget GHC.Name -> m [a]
anns = runGhc1 (GHC.findGlobalAnns deserializeWithData)


text:
const struct ConfigNames
{
	std::string manager = "manager_config.json";
	std::string detector = "detector_config.json";
	std::string recognizer = "facerec_config";
	std::string pretrainedRecognizer = "pretrained/facerec_config";
	std::string folders = "folders.json";
	std::string recognizerparams = "facerec_params_config.json";
} g_configNames;

struct ProgramParams
{
	std::string configFolder;
	std::string datasetFolder;
	std::string cascadeFolder;
	bool retrain = false;
	bool doPreprocessDataset = false;
	bool doPreprocessImage = false;
	bool doRecognizeImage = false;
	bool doTestOnDataset = false;
	std::string inputPath;
	std::string outputPath;
	bool printHelp = false;
};

enum ProgramArgIds
{
	ConfigFolder,
	DatasetFolder,
	CascadeFolder,
	Retrain,
	PreprocessDataset,
	PreprocessImage,
	RecognizeImage,
	TestDataset,
	InputPath,
	OutputPath,
	Help,
};

std::vector<ArgParser::Arg> g_programArgs = {
	{
		ProgramArgIds::ConfigFolder,
		"c",
		"config",
		"Folder with configuration files",
		true
	},
	{
		ProgramArgIds::DatasetFolder,
		"d",
		"dataset",
		"Folder with images for training",
		true
	},
	{
		ProgramArgIds::CascadeFolder,
		"ca",
		"cascade",
		"Folder with cascade classifiers",
		true
	},
	{
		ProgramArgIds::Retrain,
		"t",
		"train",
		"Disregard stored model and train recognizer again",
		false
	},
	{
		ProgramArgIds::PreprocessDataset,
		"pd",
		"preprocess-dataset",
		"Run face detection and preprocessing on dataset and write to output",
		false
	},
	{
		ProgramArgIds::PreprocessImage,
		"pi",
		"preprocess-image",
		"Run face detection and preprocessing on single image",
		false
	},
	{
		ProgramArgIds::RecognizeImage,
		"r",
		"recognize",
		"Preprocess and recognize faces on single image",
		false
	},
	{
		ProgramArgIds::TestDataset,
		"td",
		"test",
		"Test recognizer against specified dataset",
		false
	},
	{
		ProgramArgIds::InputPath,
		"i",
		"input",
		"Specify input directory or file for --preprocess-image, --recognize, and --test",
		true
	},
	{
		ProgramArgIds::OutputPath,
		"o",
		"output",
		"Specify output directory for --preprocess-image and --recognize",
		true
	},
	{
		ProgramArgIds::Help,
		"h",
		"help",
		"Print help message and exit",
		false
	},
};

class ProgramArgParser : public ArgParser
{
public:
	ProgramArgParser()
	{
		setArgInfo(g_programArgs);
	}

	ProgramParams params() { return m_params; }

protected:
	virtual bool processArg(const Arg& arg, const char* param) override
	{
		switch (arg.id)
		{
		case ConfigFolder:
			m_params.configFolder = param;
			break;

		case DatasetFolder:
			m_params.datasetFolder = param;
			break;

		case CascadeFolder:
			m_params.cascadeFolder = param;
			break;

		case Retrain:
			m_params.retrain = true;
			break;

		case PreprocessDataset:
			m_params.doPreprocessDataset = true;
			break;

		case PreprocessImage:
			m_params.doPreprocessImage = true;
			break;

		case RecognizeImage:
			m_params.doRecognizeImage = true;
			break;

		case InputPath:
			m_params.inputPath = param;
			break;

		case OutputPath:
			m_params.outputPath = param;
			break;

		case TestDataset:
			m_params.doTestOnDataset = true;
			break;

		case Help:
			m_params.printHelp = true;
			break;

		default:
			return false;
		}
		return true;
	};

private:
	ProgramParams m_params;
};

ProgramArgParser g_argParser;

ProgramParams readProgramFolders(const std::string& path)
{
	ProgramParams programFolders;
	cv::FileStorage fileStorage(path, cv::FileStorage::READ);
	if (!fileStorage.isOpened())
		return programFolders;

	programFolders.configFolder = (std::string)fileStorage["configFolder"];
	programFolders.datasetFolder = (std::string)fileStorage["datasetFolder"];
	programFolders.cascadeFolder = (std::string)fileStorage["cascadeFolder"];
	return programFolders;
}

void writeProgramFolders(const ProgramParams& config, const std::string& path)
{
	cv::FileStorage fileStorage(path, cv::FileStorage::WRITE);
	fileStorage << "configFolder" << config.configFolder;
	fileStorage << "datasetFolder" << config.datasetFolder;
	fileStorage << "cascadeFolder" << config.cascadeFolder;
}

ProgramParams prepareParams(int argc, char* argv[])
{
	ProgramParams config;
	size_t invalidArgIdx = g_argParser.parseArgs(argc - 1, argv + 1);
	if (invalidArgIdx != 0) {
		logError() << "Invalid argument:" << argv[invalidArgIdx];
		exit(1);
	}
	config = g_argParser.params();

	if (config.printHelp) {
		logInfo() << g_argParser.generateUsageMessage(argv[0]);
		exit(0);
	}

	ProgramParams storedFolders = readProgramFolders(g_configNames.folders);
	if (config.configFolder.empty()) {
		config.configFolder = storedFolders.configFolder;
	}
	if (config.datasetFolder.empty()) {
		config.datasetFolder = storedFolders.datasetFolder;
	}
	if (config.cascadeFolder.empty()) {
		config.cascadeFolder = storedFolders.cascadeFolder;
	}

	if (config.configFolder.empty()) {
		config.configFolder = ".";
	}

	if (!fs::pathExists(config.configFolder) && !fs::mkdir(config.configFolder)) {
		logError() << "Invalid config folder:" << config.configFolder;
		exit(1);
	}

	if (config.cascadeFolder.empty()) {
		config.cascadeFolder = ".";
	}

	if (!fs::isDir(config.cascadeFolder)) {
		logError() << "Invalid cascade folder:" << config.cascadeFolder;
		exit(1);
	}
	return config;
}

void preprocessDataset(ProgramParams config)
{

	if (!fs::pathExists(config.outputPath) && !fs::mkdir(config.outputPath)) {
		logError() << "Could not create folder:" << config.outputPath;
		return;
	}

	FaceDetector detector(config.cascadeFolder, fs::concatPath(config.configFolder, g_configNames.detector));

	Dataset data;
	if (config.datasetFolder.empty()) {
		logError() << "Dataset folder not set!";
		return;
	}

	std::vector<std::string> datasetContent = fs::getFilesInDir(config.datasetFolder);
	auto removeIt = std::remove_if(datasetContent.begin(), datasetContent.end(),
		[&config](const std::string& path)
	{
		return !fs::isDir(fs::concatPath(config.datasetFolder, path));
	});
	datasetContent.erase(removeIt, datasetContent.end());

	if (datasetContent.empty()) {
		logError() << "Empty datset:" << config.datasetFolder;
	}

	for (const std::string& folderName : datasetContent) {
		std::string folderPath = fs::concatPath(config.datasetFolder, folderName);
		std::vector<std::string> folderContent = fs::getFilesInDir(folderPath);
		if (folderContent.empty()) {
			logWarning() << "Empty folder:" << folderPath;
			continue;
		}

		for (const std::string imgName : folderContent) {
			std::string imgPath = fs::concatPath(folderPath, imgName);
			cv::Mat image = cv::imread(imgPath, cv::IMREAD_COLOR);
			if (image.data == nullptr) {
				logError() << "Could not read" << imgPath;
				continue;
			}

			std::string imgFolder = fs::concatPath(config.outputPath, folderName);
			if (!fs::pathExists(imgFolder) && !fs::mkdir(imgFolder)) {
				logError() << "Could not create folder:" << imgFolder;
				return;
			}

			std::vector<FaceDetector::FaceRegion> faces = detector.detect(image);
			if (faces.size() > 1) {
				logWarning() << folderName << " : more than one face found on image" << imgName;
			}
			else if (faces.empty()) {
				logWarning() << folderName << " : no faces found on image" << imgName;
				continue;
			}

			size_t createdImages = 0;
			for (const auto& face : faces) {
				std::string outImgName = imgName + "_" + std::to_string(createdImages) + ".jpg";
				cv::imwrite(fs::concatPath(imgFolder, outImgName), face.image);
				++createdImages;
			}
		}
	}
}

void processImage(ProgramParams config, FaceRecognizer* pRecognizer = nullptr)
{
	cv::Mat image = cv::imread(config.inputPath, cv::IMREAD_COLOR);
	if (image.data == nullptr) {
		logError() << "Could not read" << config.inputPath;
		return;
	}

	FaceDetector detector(config.cascadeFolder, fs::concatPath(config.configFolder, g_configNames.detector));
	size_t createdImages = 0;

	std::vector<FaceDetector::FaceRegion> faces = detector.detect(image);
	logInfo() << "Found" << faces.size() << (faces.size() == 1 ? "face" : "faces");

	for (const auto& face : faces) {
		std::string outImgName = std::to_string(createdImages);
		if (pRecognizer) {
			std::string pred = pRecognizer->predict(face.image);
			if (pred.empty()) pred = "unknown";
			logInfo() << pred;

			if (config.outputPath.empty()) {
				continue;
			}

			outImgName += '_';
			outImgName += pred;
		}
		outImgName += ".png";
		std::string outImgPath = fs::concatPath(config.outputPath, outImgName);
		if (!cv::imwrite(outImgPath, face.image)) {
			logError() << "Could not write" << outImgPath;
			return;
		}
		++createdImages;
	}
}

bool ensureOutput(std::string& output)
{
	if (output.empty()) {
		logInfo() << "Output path not specified, won't write images";
		return true;
	}
	if (!fs::pathExists(output) && !fs::mkdir(output)) {
		logError() << "Could not create folder:" << output;
		return false;
	}
	return true;
}

bool promptYN(std::string prompt, bool defaultValue = false)
{
	bool resp = false;
	std::string response;
	char ychar = defaultValue ? 'Y' : 'y';
	char nchar = defaultValue ? 'n' : 'N';
	std::string yesNo = " (";
	yesNo += ychar;
	yesNo += "(es)/";
	yesNo += nchar;
	yesNo += "(o)): ";
	while (true) {
		std::cout << prompt << yesNo;
		std::getline(std::cin, response);
		if (response.empty()) {
			return defaultValue;
		}

		std::transform(response.begin(), response.end(), response.begin(), tolower);
		if (response == "y" || response == "yes") {
			resp = true;
			break;
		} else if (response == "n" || response == "no") {
			resp = false;
			break;
		}
		std::cout << "Yes or no, please" << std::endl;
	}
	return resp;
}

void saveImages(ProgramParams config, const Dataset& newData) {
	if (!fs::pathExists(config.datasetFolder) && !fs::mkdir(config.datasetFolder)) {
		logError() << "Could not create folder:" << config.datasetFolder;
		return;
	}

	std::map<label_t, size_t> createdImages;
	for (size_t i = 0; i < newData.images().size(); ++i) {
		const cv::Mat& image = newData.images()[i];
		const label_t label = newData.labels()[i];
		const std::string& str = newData.stringByLabel(label);

		std::string imgFolder = fs::concatPath(config.datasetFolder, str);
		if (!fs::pathExists(imgFolder) && !fs::mkdir(imgFolder)) {
			logError() << "Could not create folder:" << imgFolder;
			return;
		}

		while (true) {
			size_t imgNumber = createdImages[label]++;
			std::string imgName = std::to_string(imgNumber) + ".png";
			std::string imgPath = fs::concatPath(imgFolder, imgName);
			if (fs::pathExists(imgPath)) {
				continue;
			}
			if (!cv::imwrite(imgPath, image)) {
				logError() << "Could not write" << imgPath;
				break;
			}
			break;
		}
	}
}

void testOnDataset(ProgramParams config, FaceDetector& detector, FaceRecognizer& recognizer)
{

	std::vector<std::string> datasetContent = fs::getFilesInDir(config.inputPath);
	auto removeIt = std::remove_if(datasetContent.begin(), datasetContent.end(),
		[&config](const std::string& path)
	{
		return !fs::isDir(fs::concatPath(config.inputPath, path));
	});
	datasetContent.erase(removeIt, datasetContent.end());

	if (datasetContent.empty()) {
		logError() << "Empty datset:" << config.inputPath;
	}

	size_t totalImg = 0;
	size_t detectedImg = 0;
	size_t multiDetections = 0;
	size_t correctImg = 0;
	for (const std::string& folderName : datasetContent) {
		std::string folderPath = fs::concatPath(config.inputPath, folderName);
		std::vector<std::string> folderContent = fs::getFilesInDir(folderPath);
		if (folderContent.empty()) {
			logWarning() << "Empty folder:" << folderPath;
			continue;
		}

		for (const std::string imgName : folderContent) {
			++totalImg;
			std::string imgPath = fs::concatPath(folderPath, imgName);
			cv::Mat image = cv::imread(imgPath, cv::IMREAD_COLOR);
			if (image.data == nullptr) {
				logError() << "Could not read" << imgPath;
				continue;
			}

			std::vector<FaceDetector::FaceRegion> faces = detector.detect(image);
			if (!faces.empty()) ++detectedImg;
			if (faces.size() > 1) ++multiDetections;
			for (const auto& face : faces) {
				std::string pred = recognizer.predict(face.image);
				logInfo() << pred << "(" << folderName << ")";
				if (pred == folderName) ++correctImg;
			}
		}
	}
	logInfo() << "Images total:" << totalImg;
	logInfo() << "Detected:" << detectedImg;
	logInfo() << "Multidetect:" << multiDetections;
	logInfo() << "Accuracy:" << (double)correctImg / totalImg << "(" << correctImg << "/" << totalImg << ")";
}

int main(int argc, char* argv[])
{
	ProgramParams config = prepareParams(argc, argv);

	logInfo() << "Config folder:" << config.configFolder;
	logInfo() << "Dataset folder:" << (config.datasetFolder.empty() ? "(empty)" : config.datasetFolder);
	logInfo() << "Cascade folder:" << config.cascadeFolder;

	if (config.doPreprocessDataset) {
		ensureOutput(config.outputPath);
		logInfo() << "Preprocessing dataset, output:" << config.outputPath;
		preprocessDataset(config);
		return 0;
	}

	if (config.doPreprocessImage) {
		ensureOutput(config.outputPath);
		logInfo() << "Processing" << config.inputPath << " output:" << (config.outputPath.empty() ? "(empty)" : config.outputPath);
		processImage(config);
		if (!config.doRecognizeImage) {
			return 0;
		}
	}

	std::string recognizerConfig = fs::concatPath(config.configFolder, g_configNames.recognizer);
	FaceRecognizer facerec(fs::concatPath(config.configFolder, g_configNames.recognizerparams));
	if (!config.retrain && fs::pathExists(recognizerConfig)) {
		logInfo() << "Loading pre-trained model from" << recognizerConfig;
		facerec.load(recognizerConfig);
	}

	if (config.retrain && config.datasetFolder.empty()) {
		logError() << "Can't train recognizer because dataset folder is not specified!";
		return 1;
	}

	if (config.datasetFolder.empty() && !fs::pathExists(recognizerConfig)) {
		std::string defaultRecognizerConfig = fs::concatPath(config.configFolder, g_configNames.pretrainedRecognizer);
		logInfo() << "Loading default pre-trained model from" << defaultRecognizerConfig;
		facerec.load(defaultRecognizerConfig);
	}

	if (!config.datasetFolder.empty()) {
		DatasetManager mgr;
		std::string mgrConfig = fs::concatPath(config.configFolder, g_configNames.manager);
		mgr.readConfig(mgrConfig);
		mgr.load(config.datasetFolder);
		if (config.retrain || mgr.datasetChanged() || !facerec.ready()) {
			logInfo() << "Training recognizer...";
			facerec.train(mgr.readDataset());
			logInfo() << "Done";
			if (facerec.ready()) {
				facerec.save(recognizerConfig);
				mgr.saveConfig(mgrConfig);
			}
		}
	}

	if (!facerec.ready()) {
		logError() << "Failed to start face recognizer!";
		return 1;
	}

	if (config.doRecognizeImage) {
		ensureOutput(config.outputPath);
		logInfo() << "Recognizing" << config.inputPath << " output:" << (config.outputPath.empty() ? "(empty)" : config.outputPath);
		processImage(config, &facerec);
		return 0;
	}

	FaceDetector detector(config.cascadeFolder, fs::concatPath(config.configFolder, g_configNames.detector));

	if (config.doTestOnDataset) {
		testOnDataset(config, detector, facerec);
		return 0;
	}

	cv::VideoCapture cap(0);
	if (!cap.isOpened()) {
		logError() << "Can't open capture device!";
		return 1;
	}
	logInfo() << "Press ESC to exit";

	WebcamUI ui("frame", cap, detector, facerec);
	ui.videoLoop();

	if (!facerec.newData().images().empty()) {
		if (!config.datasetFolder.empty() && promptYN("Save new images?")) {
			saveImages(config, facerec.newData());
			logInfo() << "Done";
		}
		if (promptYN("Update stored recognizer with new data?")) {
			facerec.save(recognizerConfig);
			logInfo() << "Done";
		}
	}

	writeProgramFolders(config, g_configNames.folders);
	return 0;
}


text:
<?php declare(strict_types=1);

namespace Ajaxray\PHPWatermark\CommandBuilders;

interface WatermarkCommandBuilderInterface
{
    /**
     * Build the imagemagick shell command for watermarking with Image
     *
     * @param string $markerImage The image file path to watermark with
     * @param string $output The watermarked output file
     * @param array $options
     * @return string ImageMagick command to watermark with image
     */
    public function getImageMarkCommand(string $markerImage, string $output, array $options): string;

    /**
     * Build the imagemagick shell command for watermarking with Text
     *
     * @param string $text The text content to watermark with
     * @param string $output The watermarked output file
     * @param array $options
     * @return string ImageMagick command to watermark with text
     */
    public function getTextMarkCommand(string $text, string $output, array $options): string;
}


text:
package com.nanlabs.grails.plugin.logicaldelete;

import java.lang.reflect.Modifier;

import org.codehaus.groovy.ast.ASTNode;
import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.ast.expr.ConstantExpression;
import org.codehaus.groovy.control.CompilePhase;
import org.codehaus.groovy.control.SourceUnit;
import org.codehaus.groovy.grails.compiler.injection.GrailsASTUtils;
import org.codehaus.groovy.transform.ASTTransformation;
import org.codehaus.groovy.transform.GroovyASTTransformation;

@GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION)
public class LogicalDeleteASTTRansformation implements ASTTransformation{

	public final static String DELETED_FIELD_NAME = "deleted";
	public final static String LIST_DELETED_METHOD_NAME = "listDeleted";
	public final static int CLASS_NODE_ORDER = 1;

	@Override
	public void visit(ASTNode[] nodes, SourceUnit source) {
		if(!validate(nodes))return;
		ClassNode classNode = (ClassNode)nodes[CLASS_NODE_ORDER];
		addDeletedProperty(classNode);
		addListDeletedMethod(classNode);
		implementDeletedDomainClassInterface(classNode);
	}

	private boolean validate(ASTNode[] nodes){
		return nodes != null && nodes[0] != null && nodes[1] != null;
	}

	private void addDeletedProperty(ClassNode node) {
		if(!GrailsASTUtils.hasOrInheritsProperty(node, DELETED_FIELD_NAME)){
			node.addProperty(DELETED_FIELD_NAME, Modifier.PUBLIC, new ClassNode(Boolean.class), ConstantExpression.FALSE, null, null);
		}
	}

	private void addListDeletedMethod(ClassNode node) {

	}

	private void implementDeletedDomainClassInterface(ClassNode node){
		ClassNode iNode = new ClassNode(LogicalDeleteDomainClass.class);
		if(!iNode.implementsInterface(iNode)){
			node.addInterface(iNode);
		}
	}

}


text:
package iurii.job.interview.topcoder.srm503;

/**
 * Problem Statement
 * ����
 * Let's say you have a binary string such as the following:
 * 011100011
 * One way to encrypt this string is to add to each digit the sum of its adjacent digits. For example, the above string would become:
 * 123210122
 * In particular, if P is the original string, and Q is the encrypted string, then Q[i] = P[i-1] + P[i] + P[i+1] for all digit positions i. Characters off the left and right edges of the string are treated as zeroes.
 * An encrypted string given to you in this format can be decoded as follows (using 123210122 as an example):
 * Assume P[0] = 0.
 * Because Q[0] = P[0] + P[1] = 0 + P[1] = 1, we know that P[1] = 1.
 * Because Q[1] = P[0] + P[1] + P[2] = 0 + 1 + P[2] = 2, we know that P[2] = 1.
 * Because Q[2] = P[1] + P[2] + P[3] = 1 + 1 + P[3] = 3, we know that P[3] = 1.
 * Repeating these steps gives us P[4] = 0, P[5] = 0, P[6] = 0, P[7] = 1, and P[8] = 1.
 * We check our work by noting that Q[8] = P[7] + P[8] = 1 + 1 = 2. Since this equation works out, we are finished, and we have recovered one possible original string.
 * Now we repeat the process, assuming the opposite about P[0]:
 * Assume P[0] = 1.
 * Because Q[0] = P[0] + P[1] = 1 + P[1] = 1, we know that P[1] = 0.
 * Because Q[1] = P[0] + P[1] + P[2] = 1 + 0 + P[2] = 2, we know that P[2] = 1.
 * Now note that Q[2] = P[1] + P[2] + P[3] = 0 + 1 + P[3] = 3, which leads us to the conclusion that P[3] = 2.
 * However, this violates the fact that each character in the original string must be '0' or '1'.
 * Therefore, there exists no such original string P where the first digit is '1'.
 * Note that this algorithm produces at most two decodings for any given encrypted string.
 * There can never be more than one possible way to decode a string once the first binary digit is set.
 * Given a String message, containing the encrypted string, return a String[] with exactly two elements.
 * The first element should contain the decrypted string assuming the first character is '0';
 * the second element should assume the first character is '1'.
 * If one of the tests fails, return the string "NONE" in its place.
 * For the above example, you should return {"011100011", "NONE"}.
 */
public class BinaryCode {
    public String[] decode(String message) {
        String[] results = new String[2];
        results[0] = decode(message, false);
        results[1] = decode(message, true);
        return results;
    }

    private String decode(String message, boolean firstDigit) {
        String decodedString = firstDigit ? "1" : "0";
        for (int i = 0; i < message.length() - 1; i++) {
            int nextDigit = convertToDigit(message.substring(i, i + 1)) -
                    ((i + 1) < message.length() ? convertToDigit(decodedString.substring(i, i + 1)) : 0) -
                    ((i - 1) > 0 ? convertToDigit(decodedString.substring(i - 1, i)) : 0);
            if (nextDigit != 0 && nextDigit != 1) {
                return "NONE";
            } else {
                decodedString += nextDigit;
            }
        }
        return decodedString;
    }

    private int convertToDigit(String digitString) {
        return "".equals(digitString) ? 0 : Integer.parseInt(digitString);
    }
}


text:
import React, {Component} from 'react';
import { HashRouter as Router, Route, Switch } from "react-router-dom";
import { createBrowserHistory } from 'history';
import '../css/App.css';
import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap/dist/js/bootstrap.js';
import 'react-bootstrap-table-next/dist/react-bootstrap-table2.min.css';
import 'react-bootstrap-table-next/dist/react-bootstrap-table-next.min.js';
import 'react-bootstrap-table2-paginator/dist/react-bootstrap-table2-paginator.min.css';
import 'react-bootstrap-table2-paginator/dist/react-bootstrap-table2-paginator.min.js';
import 'react-bootstrap-table2-toolkit/dist/react-bootstrap-table2-toolkit.min.css';
import 'react-bootstrap-table2-toolkit/dist/react-bootstrap-table2-toolkit.min.js';
import LoginContainer from './LoginContainer'
import LogoutContainer from './LogoutContainer'
import MainContainer from './MainContainer'
import AuthenticationContext from "../context/AuthenticationContext";
import VersionContext from "../context/VersionContext";
import axios from "axios";
import ContextContext from "../context/ContextContext";

export const history = createBrowserHistory({
    basename: process.env.PUBLIC_URL
});

class App extends Component {

    constructor(props) {
        super(props);
        this.getVersion = this.getVersion.bind(this);
        this.getContext = this.getContext.bind(this);

        this.updateAuthentication = (authentication) => {
            this.setState({
                authentication: authentication
            });
        }

        this.state = {
            authentication: {},
            updateAuthentication: this.updateAuthentication,
            version: "1.0",
            context: "castlemock"
        };

        this.getVersion();
        this.getContext();
    }

    getVersion() {
        axios
            .get(process.env.PUBLIC_URL + "/api/rest/core/version")
            .then(response => {
                this.setState({version: response.data.version})
            });
    }

    getContext() {
        axios
            .get(process.env.PUBLIC_URL + "/api/rest/core/context")
            .then(response => {
                this.setState({context: response.data.context})
            });
    }

    render() {
        return (
            <ContextContext.Provider value={this.state.context}>
                <VersionContext.Provider value={this.state.version}>
                    <AuthenticationContext.Provider value={this.state}>
                        <div className = "site-wrapper">
                            <Router>
                                <Switch>
                                    <Route path="/web/login"  component={LoginContainer} />
                                    <Route path="/web/logout"  component={LogoutContainer} />
                                    <Route path="/web/*"  component={MainContainer} />
                                    <Route path="/*"  component={MainContainer} />
                                    <Route path=""  component={MainContainer} />
                                </Switch>
                            </Router>
                        </div>
                    </AuthenticationContext.Provider>
                </VersionContext.Provider>
            </ContextContext.Provider>
        );
    }
}

export default App;


text:
package net.sourcewalker.vfrmap.sensor;

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

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.Log;
import android.view.Surface;
import android.view.WindowManager;

public class CompassManager implements SensorEventListener {

    private boolean resumed;

    public interface Listener {

        public void onUpdateCompass(CompassManager sender, float azimuth, float pitch, float roll);
    }

    /**
     * Maximum difference of sensor measurement timestamps in nanoseconds.
     * (100ms)
     */
    private static final long MAX_TIMESTAMP_DIFF = 100000000;

    private static final String TAG = "CompassManager";

    /**
     * Damping factor for sensor filtering.
     */
    private static final float LOWPASS_ALPHA = 0.05f;

    private final float[] R = new float[16];
    private final float[] tmpR = new float[16];
    private final float[] accelValues = new float[3];
    private final float[] magnetValues = new float[3];
    private final float[] orientation = new float[3];

    private SensorManager sensorManager;
    private ArrayList<Listener> listenerList;
    private Sensor accelerometer = null;
    private Sensor magnetometer = null;
    private long accelTime = 0;
    private long magnetTime = 0;
    private int displayRotation = 0;

    public void setDisplayOrientation(int displayOrientation) {
        this.displayRotation = displayOrientation;
    }

    public CompassManager(Context context) {
        listenerList = new ArrayList<Listener>();
        sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
        List<Sensor> sensorList = sensorManager.getSensorList(Sensor.TYPE_ALL);
        for (Sensor sensor : sensorList) {
            switch (sensor.getType()) {
            case Sensor.TYPE_ACCELEROMETER:
                accelerometer = sensor;
                break;
            case Sensor.TYPE_MAGNETIC_FIELD:
                magnetometer = sensor;
                break;
            }
        }

        updateDisplayRotation(context);
    }

    public void updateDisplayRotation(Context context) {
        WindowManager windowService = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        displayRotation = windowService.getDefaultDisplay().getRotation();
    }

    public void addUpdateListener(Listener listener) {
        listenerList.add(listener);
    }

    public void removeUpdateListener(Listener listener) {
        listenerList.remove(listener);
    }

    public void fireUpdateEvent(float azimuth, float pitch, float roll) {
        for (Listener l : listenerList) {
            l.onUpdateCompass(this, azimuth, pitch, roll);
        }
    }

    public void resume() {
        if (!resumed) {
            sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_UI);
            sensorManager.registerListener(this, magnetometer, SensorManager.SENSOR_DELAY_UI);
            resumed = true;
        }
    }

    public void pause() {
        if (resumed) {
            sensorManager.unregisterListener(this);
            resumed = false;
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        if (event.sensor.equals(accelerometer)) {
            accelTime = event.timestamp;
            copyArrayLowPass(event.values, accelValues);
        }
        if (event.sensor.equals(magnetometer)) {
            magnetTime = event.timestamp;
            copyArrayLowPass(event.values, magnetValues);
        }
        if (haveValidMeasurements()) {
            float[] orientation = calculateOrientation();
            if (orientation != null) {
                fireUpdateEvent(orientation[0], orientation[1], orientation[2]);
            }
        }
    }

    private void copyArrayLowPass(float[] source, float[] destination) {
        for (int i = 0; i < destination.length; i++) {
            destination[i] = destination[i] + LOWPASS_ALPHA * (source[i] - destination[i]);
        }
    }

    private boolean haveValidMeasurements() {
        if (accelTime != 0 && magnetTime != 0) {
            if (Math.abs(magnetTime - accelTime) < MAX_TIMESTAMP_DIFF) {
                return true;
            }
        }
        return false;
    }

    private float[] calculateOrientation() {
        boolean success = SensorManager.getRotationMatrix(R, null, accelValues, magnetValues);
        if (success) {
            float[] displayRemapR = getRemappedMatrix(R);
            SensorManager.getOrientation(displayRemapR, orientation);
            return orientation;
        } else {
            return null;
        }
    }

    private float[] getRemappedMatrix(final float[] R) {
        switch (displayRotation) {
        case Surface.ROTATION_0:
            break;
        case Surface.ROTATION_180:
            SensorManager.remapCoordinateSystem(R, SensorManager.AXIS_MINUS_X, SensorManager.AXIS_MINUS_Y, tmpR);
            return tmpR;
        case Surface.ROTATION_90:
        case Surface.ROTATION_270:
            SensorManager.remapCoordinateSystem(R, SensorManager.AXIS_X, SensorManager.AXIS_Z, tmpR);
            return tmpR;
        default:
            Log.w(TAG, "Unknown display orientation: " + displayRotation);
        }
        return R;
    }
}


text:
/**
 * This module specifies a component for the page header.
 *
 * @module MenuHeader.react
 */

var React = require('react');
var CartStore = require('../../stores/CartStore');
var PriceUtils = require('../../utils/PriceUtils');

function _getStateFromStores() {
  return {
    cartItems: CartStore.getAll()
  };
}

var MenuHeader = React.createClass({

  getInitialState: function() {
    return _getStateFromStores();
  },

  componentDidMount: function() {
    CartStore.addChangeListener(this._onChange);
  },

  componentWillUnmount: function() {
    CartStore.removeChangeListener(this._onChange);
  },

  render: function() {
    var count = this.state.cartItems.length;
    var suffix = count !== 1 ? 's' : '';
    var price = this.state.cartItems.reduce(function(price, cartItem) {
      return price + cartItem.menuItem.price;
    }, 0);

    return (

            Ristorante Italiano

        <button
          className="cart-count">

              Cart: {count} item{suffix}

              ({PriceUtils.formatPrice(price)})

        </button>

    );
  },

  /**
   * Event handler for 'change' events coming from the CartStore
   */
  _onChange: function() {
    this.setState(_getStateFromStores());
  }

});

module.exports = MenuHeader;


text:
package nl.rug.search.cpptool.runtime;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface ExtendedData {
    Class<?>[] value();
}


text:
using GraphLayout
using factor

if (OS_NAME != :Windows)
  using GraphViz
  function make_dot(params, name)

      s = string("digraph ", name, " {")
      # Take each variable by turn
      for (varname, set) in params
          #println("Variable with name: ", varname)
          for var in set
              #println("index: ", var[2], " distribution and deps: ", var[7], typeof(var[7]))
              if !(typeof(var[7]) in [Symbol, Int64, Int])
                  #println("trying var", var[7], " with type ", typeof(var[7]))
                  for othervar in var[7][2]
                      ov = string(othervar)
                      if contains(ov, "[")
                          ov = replace(replace(ov, "[", "_"), "]", "")
                      end
                      s = string(s, ov, " -> ", varname, "_", var[2], ";\n")
                  end
              end
          end
      end

      s = string(s, "}")

      #println("---------")
      #println(s)

      return s
  end

  function plot_graph(params, name)
      return Graph(make_dot(params, name))
  end
end

function save_svg(g::FactorGraph, name)
  am = full(adjacency_matrix(g.G))
  loc_x, loc_y = layout_spring_adj(am)
  draw_layout_adj(am, loc_x, loc_y, filename=name)
end


text:
title: Tuna Netra "Melek" Media dalam Pemenuhan Kebutuhan Informasi bagi Penyandang
  Cacat
date: 2011-09-16 11:08:00 +07:00
nohibah: 560
inisiator: Radio Komunitas Suara Kota 107,7 FM
lokasi: Bandar Lampung
dana: 200 Juta Rupiah
topik: Pemantauan media
lama: Januari 2012 – Januari 2013
deskripsi: Hingga saat ini belum ada media yang mendedikasikan diri menyediakan informasi
  bagi penyandang tuna netra. Dan, hingga kini penyandang tuna netra seperti terasing
  dari masyarakat karena minimnya informasi yang mereka miliki. Dengan keberadaan
  radio komunitas (rakom) dan pemanfaatan TIK, penyandang tuna netra dapat mengawasi
  media agar lebih kebutuhan informasinya terpenuhi. Selain itu, penyandang tuna netra
  dapat mengkritisi kebijakan publik agar lebih ramah dan peduli terhadap penyandang
  tuna netra. Untuk itu, perlu dibangun kemampuan dan penguatan penyandang tuna netra
  dalam mempergunakan TIK untuk menerima dan menyebarluaskan informasi dalam bentuk
  TIK center di panti tunanetra. Selanjutnya penyandang tuna netra diberikan kesempatan
  terlibat mengelola informasi di rakom dalam program siaran yang didedikasikan untuk
  penyandang tuna netra dengan memanfaatkan TIK. Untuk menindaklanjuti kebutuhan informasi
  penyandang tuna netra, informasi diteruskan kepada Pemerintah dan Legislatif dalam
  bentuk konvergensi media. Dengan tersebarluaskannya informasi yang dikelola rakom
  dan penyandang tuna netra, diharapkanterbangun inisatif Pemerintah dalam merumuskan
  kebijakan publik pro penyandang cacat.
masalah: Mendorong peningkatan kapasitas penyandang tuna netra dalam mengelola informasi,
  mendorong peran penyandang tuna netra dalam meliterasi media dengan fokus kebijakan
  publik pro penyandang cacat, mendorong peningkatan kemampuan penyandang tuna netra
  dalam memanfaatkan TIK untuk pengelolaan informasi, mendorong tersebarluaskannya
  informasi yang dikelola, dan penyandang tuna netra kepada khalayak
solusi: |-
  Mendampingi dan memperkuat kapasitas penyandang tuna netra dalam mengelola informasi dan meliterasi media, memproduksi informasi yang dapat dikonsumsi penyandang tuna netra, menyediakan sarana dan prasarana pusat TIK yang ramah, meyandang tuna netra untuk mengelola informasi, dan mengkonvergensikan dan menyebarluaskan informasi yang dikelola penyandang tuna netra kepada klayak.
  Pihak yang menerima manfaat dari proyek ini adalah penyandang tuna netra, radio komunitas, dan pemerintah serta legislatif Kota Bandar Lampung.
keberhasilan: Tersedianya rekam proses pengelolaan informasi literasi media yang dilakukan
  penyandang tuna netra, terbangun dan termanfaatkan pusat TIK bagi pengelolaan informasi
  yang dilakukan penyenadang tuna netra, tersedianya program siaran rakom sebagai
  saluran informasi bagi penyandang tuna netra yang terkonvergensi, tersebarluaskannya
  informasi yang dikelola rakom dan penyandang tuna netra kepada khalayak, dan terbangunnya
  inisiatif Pemerintah dan Legislatif Kota Bandar Lampung dalam menyusun kebijakan
  publik yang pro penyandang cacat.
organisasi: Radio Komunitas Suara Kota 107,7 FM
diuntungkan: penyandang tuna netra, radio komunitas, dan pemerintah serta legislatif
  Kota Bandar Lampung
layout: hibahcmb
---

![560](/static/img/hibahcmb/560.png){: .img-responsive }{: width="350" }

### {{ page.nohibah }} - {{ page.title }}

---


text:
import styled from 'styled-components'

import Img from '@/Img'
import css, { theme } from '@/utils/css'

export const Wrapper = styled.div`
  ${css.flexColumnGrow('align-center')};
  margin-top: 10px;
`
export const CountDesc = styled.div`
  color: ${theme('thread.articleDigest')};
  margin-bottom: 10px;
`
export const DescNumber = styled.span`
  color: #139c9e;
  font-weight: bold;
`
export const NextDesc = styled.div`
  margin-top: 15px;
  color: ${theme('thread.articleDigest')};
`
export const NextStepBtn = styled.span`
  border: 1px solid;
  border-color: ${theme('thread.articleTitle')};
  padding: 0 3px;
  border-radius: 4px;
  margin-left: 6px;
  color: ${theme('thread.articleTitle')};

  &:hover {
    color: ${theme('banner.title')};
    font-weight: bold;
    cursor: pointer;
    text-decoration: underline;
  }
`
export const PaymentPic = styled(Img)`
  width: 200px;
  height: auto;
  display: block;
`


text:
package io.astefanutti.metrics.cdi;

import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.annotation.CachedGauge;
import com.codahale.metrics.annotation.Counted;
import com.codahale.metrics.annotation.ExceptionMetered;
import com.codahale.metrics.annotation.Gauge;
import com.codahale.metrics.annotation.Metered;
import com.codahale.metrics.annotation.Timed;

import javax.annotation.Priority;
import javax.inject.Inject;
import javax.interceptor.AroundConstruct;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.concurrent.TimeUnit;

@Interceptor
@MetricsBinding
@Priority(Interceptor.Priority.LIBRARY_BEFORE)
// See http://docs.oracle.com/javaee/7/tutorial/doc/interceptors.htm
/* package-private */ class MetricsInterceptor {

    private final MetricRegistry registry;

    private final MetricResolver resolver;

    @Inject
    private MetricsInterceptor(MetricRegistry registry, MetricResolver resolver) {
        this.registry = registry;
        this.resolver = resolver;
    }

    @AroundConstruct
    private Object metrics(InvocationContext context) throws Exception {
        // Registers the present bean constructor metrics
        registerMetrics(context.getConstructor());

        // Registers the present methods metrics over the bean type hierarchy
        Class<?> bean = context.getConstructor().getDeclaringClass();
        do {
            // TODO: discover annotations declared on implemented interfaces
            for (Method method : bean.getDeclaredMethods())
                if (!method.isSynthetic() && !Modifier.isPrivate(method.getModifiers()))
                    registerMetrics(method);
            bean = bean.getSuperclass();
        } while (!Object.class.equals(bean));

        Object target = context.proceed();

        // Registers the present gauges over the bean type hierarchy after the target is constructed as it is required for the gauge invocations
        bean = context.getConstructor().getDeclaringClass();
        do {
            // TODO: discover annotations declared on implemented interfaces
            for (Method method : bean.getDeclaredMethods()) {
                MetricResolver.Of<CachedGauge> cachedGauge = resolver.cachedGauge(method);
                if (cachedGauge.isPresent())
                    registry.register(cachedGauge.metricName(), new CachingGauge(new ForwardingGauge(method, context.getTarget()), cachedGauge.metricAnnotation().timeout(), cachedGauge.metricAnnotation().timeoutUnit()));

                MetricResolver.Of<Gauge> gauge = resolver.gauge(method);
                if (gauge.isPresent())
                    registry.register(gauge.metricName(), new ForwardingGauge(method, context.getTarget()));
            }
            bean = bean.getSuperclass();
        } while (!Object.class.equals(bean));

        return target;
    }

    private <E extends Member & AnnotatedElement> void registerMetrics(E element) {
        MetricResolver.Of<Counted> counted = resolver.counted(element);
        if (counted.isPresent())
            registry.counter(counted.metricName());

        MetricResolver.Of<ExceptionMetered> exceptionMetered = resolver.exceptionMetered(element);
        if (exceptionMetered.isPresent())
            registry.meter(exceptionMetered.metricName());

        MetricResolver.Of<Metered> metered = resolver.metered(element);
        if (metered.isPresent())
            registry.meter(metered.metricName());

        MetricResolver.Of<Timed> timed = resolver.timed(element);
        if (timed.isPresent())
            registry.timer(timed.metricName());
    }

    private static final class CachingGauge extends com.codahale.metrics.CachedGauge<Object> {

        private final com.codahale.metrics.Gauge<?> gauge;

        private CachingGauge(com.codahale.metrics.Gauge<?> gauge, long timeout, TimeUnit timeoutUnit) {
            super(timeout, timeoutUnit);
            this.gauge = gauge;
        }

        @Override
        protected Object loadValue() {
            return gauge.getValue();
        }
    }

    private static final class ForwardingGauge implements com.codahale.metrics.Gauge<Object> {

        private final Method method;

        private final Object object;

        private ForwardingGauge(Method method, Object object) {
            this.method = method;
            this.object = object;
            method.setAccessible(true);
        }

        @Override
        public Object getValue() {
            return invokeMethod(method, object);
        }
    }

    private static Object invokeMethod(Method method, Object object) {
        try {
            return method.invoke(object);
        } catch (IllegalAccessException | InvocationTargetException cause) {
            throw new IllegalStateException("Error while calling method [" + method + "]", cause);
        }
    }
}


text:
package org.bouncycastle.cavp.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

import org.bouncycastle.util.encoders.Hex;

public class DsaTest
{
    private String baseDir;
    private ProcessorFactoryProducer producer;

    public DsaTest(String baseDir, ProcessorFactoryProducer producer)
        throws Exception
    {
        this.baseDir = baseDir;
        this.producer = producer;
    }

    public List<String> run()
        throws Exception
    {
        List<String> errors = new ArrayList<String>();
        File dataDir = new File(baseDir);

        for (File data : dataDir.listFiles())
        {
            if (data.getName().startsWith("PQGVer"))
            {
                processPQGVer(data, null, errors);
            }
            else
            {
                System.err.println("ignoring " + data);
            }

            if (!errors.isEmpty())
            {
                return errors;
            }
        }

        return errors;
    }

    private void processPQGVer(File f, DigestProcessorFactory processorFactory, List<String> errors)
        throws Exception
    {
        BufferedReader bRd = new BufferedReader(new FileReader(f));

        String line = bRd.readLine();
        while (line.startsWith("#"))
        {
            line = bRd.readLine();
        }

        String mod = bRd.readLine();

        while (bRd.readLine() != null)
        {
            String line1 = bRd.readLine();
            if (line1 == null || line1.startsWith("["))
            {
                mod = line;
                continue;
            }

            BigInteger P = new BigInteger(1, (byte[])parseLine(line1).getValue());
            BigInteger Q = new BigInteger(1, (byte[])parseLine(bRd).getValue());
            BigInteger G = new BigInteger(1, (byte[])parseLine(bRd).getValue());
            byte[] seed = (byte[])parseLine(bRd).getValue();
            Integer c = (Integer)parseLine(bRd).getValue();
            byte[] H = (byte[])parseLine(bRd).getValue();
            String result = (String)parseLine(bRd).getValue();

            System.err.println("P " + P.bitLength());
        }

        bRd.close();
    }

    private Entry parseLine(BufferedReader bRd)
        throws IOException
    {
        return parseLine(bRd.readLine());
    }

    private Entry parseLine(String line)
        throws IOException
    {
        if (line == null || line.isEmpty())
        {
            return null;
        }

        String[] vals = line.split(" = ");

        return new Entry(vals[0], vals[1]);
    }

    public String getName()
    {
        return "SHA";
    }

    static class Entry
    {
        private final String name;
        private final String value;

        Entry(String name, String value)
        {
           this.name = name;
            this.value = value;
        }

        String getName()
        {
            return name;
        }

        Object getValue()
        {
            if (name.equals("c"))
            {
                return Integer.valueOf(value);
            }
            else if (name.equals("Result"))
            {
                return value;
            }
            else
            {
                return Hex.decode(value);
            }
        }
    }
}


text:
FACEBOOK_INFO = {
  "id" => "12345",
  "link" => "http://facebook.com/john_doe",
  "email" => "user@example.com",
  "first_name" => "John",
  "last_name" => "Doe",
  "website" => "http://www.example.com"
}

Before("@omniauth_test") do
  OmniAuth.config.test_mode = true

  # the symbol passed to mock_auth is the same as the name of the provider set up in the initializer
  OmniAuth.config.mock_auth[:facebook] = {
      "uid" => "12345",
      "provider" => "facebook",
      "user_info" => { "nickname" => "Johny" },
      "credentials" => { "token" => "exampletoken" },
      "info" => FACEBOOK_INFO
  }
end

After("@omniauth_test") do
  OmniAuth.config.test_mode = false
end


text:
<!DOCTYPE html>
<!--
Copyright 2016 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->

<link rel="import" href="/tracing/core/test_utils.html">

<link rel="import" href="/dashboard/elements/bisect-button.html">
<link rel="import" href="/dashboard/static/testing_common.html">

<script>
'use strict';

tr.b.unittest.testSuite(function() {

  var testOptions = {
    tearDown: function() {
      testing_common.clearXhrMock();
      testing_common.clearFixture();
    }
  };

  test('instantiate_basic', function() {
    var button = document.createElement('bisect-button');
    this.addHTMLOutput(button);
  }, testOptions);

  test('canBisect false if there is no bisectInfo', function() {
    var button = document.createElement('bisect-button');
    testing_common.addToFixture(button);
    button.bugId = 500500;
    assert.isFalse(button.canBisect);
  }, testOptions);

  test('empty', function() {
  }, testOptions);

  test('canBisect set to true for valid tests after check', function() {
    testing_common.addXhrMock(
        '/can_bisect?test_path=ChromiumPerf%2Flinux%2Fsunspider%2FTotal' +
        '&start_revision=323400&end_revision=323500',
        'true');

    var button = document.createElement('bisect-button');
    testing_common.addToFixture(button);
    button.bisectInfo = {
      'testPath': 'ChromiumPerf/linux/sunspider/Total',
      'goodRev': 323400,
      'badRev': 323500
    };

    return new Promise(function(resolve) {
      function check() {
        assert.isTrue(button.canBisect);
        resolve();
      }
      setTimeout(check, 10);
    });
  }, testOptions);

  test('canBisect set to false for invalid tests after check', function() {
    testing_common.addXhrMock(
        '/can_bisect?test_path=Chromium%2Flinux%2Fsizes' +
        '&start_revision=323400&end_revision=323500',
        'false');

    var button = document.createElement('bisect-button');
    testing_common.addToFixture(button);
    button.bisectInfo = {
      'testPath': 'Chromium/linux/sizes',
      'goodRev': 323400,
      'badRev': 323500
    };

    return new Promise(function(resolve) {
      function check() {
        assert.isFalse(button.canBisect);
        resolve();
      }
      setTimeout(check, 100);
    });
  }, testOptions);

});
</script>


text:
define(function(require){

	var Router = require('joss/mvc/Router');

	//keep track of how many times we change the hash, and erase history
	//afterwards.
	var routeCount = 0;

	var _route = function(hash) {
		setTimeout(function() {
			window.location.hash = hash;
		}, routeCount * 20);
		routeCount++;
	};

	var _finish = function(callback) {
		callback = callback || function() {};
		setTimeout(function() {
			callback();
			//remove history caused by changing window hash
			history.go(-1 * routeCount);
			routeCount = 0;
			start();
		}, (routeCount + 1) * 20);
	};

	module('joss/mvc/Router');

	asyncTest('Basics', function() {

		var count = {};

		var TestRouter = Router.extend({

			'*': function() {
				count['*'] = count['*'] || 0;
				count['*']++;
			},

			'*?': function() {
				count['*?'] = count['*?'] || 0;
				count['*?']++;
			},

			'/foo': function(fragment) {
				count[fragment] = count[fragment] || 0;
				count[fragment]++;
			},

			'/bar': function(fragment) {
				count[fragment] = count[fragment] || 0;
				count[fragment]++;
			}

		});

		TestRouter();

		var routes = ['foo', 'bar', 'baz', 'foo'];
		routes.forEach(function(hash) {
			_route('/' + hash);
		});

		_finish(function() {
			strictEqual(count['*'], 4, '* matched all hashchange events');
			strictEqual(count['*?'], 1, '*? matched all not-explicitly-defined hashchange events');
			strictEqual(count['/foo'], 2, '/foo matched twice');
			strictEqual(count['/bar'], 1, '/bar matched once');
		});

	});

	asyncTest('Arguments', function() {

		var TestRouter = Router.extend({

			'/{arg1}/{arg2}': function(arg1, arg2) {
				strictEqual(arg1, 'foo', 'arg1 parsed');
				strictEqual(arg2, 'bar', 'arg2 parsed');
			}

		});

		TestRouter();

		_route('/foo/bar/');

		_finish();

	});

});


text:
FROM rolando/base

RUN apt-get install -y gcc make g++ build-essential libc6-dev tcl

RUN wget -qO - http://download.redis.io/redis-stable.tar.gz | tar zxf -
RUN (cd /redis-stable && make all test)

RUN mkdir /redis-data
VOLUME ["/redis-data"]

EXPOSE 6379
ENTRYPOINT ["/redis-stable/src/redis-server", "--dir", "/redis-data"]


text:
"""
    Model that simulates the 0-60 acceleration time, the EPA city fuel economy,
    and the EPA highway fuel economy of a Vehicle.
"""

from openmdao.examples.enginedesign.driving_sim import SimAcceleration, \
    SimEconomy
from openmdao.examples.enginedesign.vehicle import Vehicle
from openmdao.main.api import Assembly

class VehicleSim2(Assembly):
    """Optimization of a Vehicle."""

    def configure(self):
        """ Configures a new Assembly for vehicle performance optimization."""

        # Create Vehicle instance
        self.add('vehicle', Vehicle())

        # Create Driving Simulation instances
        self.add('sim_acc', SimAcceleration())
        self.add('sim_EPA_city', SimEconomy())
        self.add('sim_EPA_highway', SimEconomy())

        # add Sims to default workflow
        self.driver.workflow.add(['sim_acc', 'sim_EPA_city', 'sim_EPA_highway'])

        # Add vehicle to sim workflows.
        self.sim_acc.workflow.add('vehicle')
        self.sim_EPA_city.workflow.add('vehicle')
        self.sim_EPA_highway.workflow.add('vehicle')

        # Acceleration Sim setup
        self.sim_acc.add_parameter('vehicle.velocity', name='velocity',
                                   low=0.0, high=150.0)
        self.sim_acc.add_parameter('vehicle.throttle', name='throttle',
                                   low=0.01, high=1.0)
        self.sim_acc.add_parameter('vehicle.current_gear', name='gear',
                                   low=0, high=5)
        self.sim_acc.add_objective('vehicle.acceleration', name='acceleration')
        self.sim_acc.add_objective('vehicle.overspeed', name='overspeed')

        # EPA City MPG Sim Setup
        self.sim_EPA_city.add_parameter('vehicle.velocity', name='velocity',
                                        low=0.0, high=150.0)
        self.sim_EPA_city.add_parameter('vehicle.throttle', name='throttle',
                                        low=0.01, high=1.0)
        self.sim_EPA_city.add_parameter('vehicle.current_gear', name='gear',
                                        low=0, high=5)
        self.sim_EPA_city.add_objective('vehicle.acceleration', name='acceleration')
        self.sim_EPA_city.add_objective('vehicle.fuel_burn', name='fuel_burn')
        self.sim_EPA_city.add_objective('vehicle.overspeed', name='overspeed')
        self.sim_EPA_city.add_objective('vehicle.underspeed', name='underspeed')
        self.sim_EPA_city.profilename = 'EPA-city.csv'

        # EPA Highway MPG Sim Setup
        self.sim_EPA_highway.add_parameter('vehicle.velocity', name='velocity',
                                           low=0.0, high=150)
        self.sim_EPA_highway.add_parameter('vehicle.throttle', name='throttle',
                                           low=0.01, high=1.0)
        self.sim_EPA_highway.add_parameter('vehicle.current_gear', name='gear',
                                           low=0, high=5)
        self.sim_EPA_highway.add_objective('vehicle.acceleration', name='acceleration')
        self.sim_EPA_highway.add_objective('vehicle.fuel_burn', name='fuel_burn')
        self.sim_EPA_highway.add_objective('vehicle.overspeed', name='overspeed')
        self.sim_EPA_highway.add_objective('vehicle.underspeed', name='underspeed')
        self.sim_EPA_highway.profilename = 'EPA-highway.csv'

if __name__ == "__main__":
    from openmdao.main.api import set_as_top

    my_sim = VehicleSim2()
    set_as_top(my_sim)

    my_sim.run()

    print "Time (0-60): ", my_sim.sim_acc.accel_time
    print "City MPG: ", my_sim.sim_EPA_city.fuel_economy
    print "Highway MPG: ", my_sim.sim_EPA_highway.fuel_economy


text:
#ifndef  BOOST_SERIALIZATION_BOOST_UNORDERED_SET_HPP
#define BOOST_SERIALIZATION_BOOST_UNORDERED_SET_HPP

// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif

/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// unordered_set.hpp: serialization for boost unordered_set templates

// (C) Copyright 2002 Robert Ramey - http://www.rrsd.com .
// (C) Copyright 2014 Jim Bell
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

//  See http://www.boost.org for updates, documentation, and revision history.

#include <boost/config.hpp>

#include <boost/unordered_set.hpp>

#include <boost/serialization/unordered_collections_save_imp.hpp>
#include <boost/serialization/unordered_collections_load_imp.hpp>
#include <boost/serialization/archive_input_unordered_set.hpp>
#include <boost/serialization/split_free.hpp>

namespace boost {
namespace serialization {

template<
    class Archive,
    class Key,
    class HashFcn,
    class EqualKey,
    class Allocator
>
inline void save(
    Archive & ar,
    const boost::unordered_set<Key, HashFcn, EqualKey, Allocator> &t,
    const unsigned int /*file_version*/
){
    boost::serialization::stl::save_unordered_collection<
        Archive,
        boost::unordered_set<Key, HashFcn, EqualKey, Allocator>
    >(ar, t);
}

template<
    class Archive,
    class Key,
    class HashFcn,
    class EqualKey,
    class Allocator
>
inline void load(
    Archive & ar,
    boost::unordered_set<Key, HashFcn, EqualKey, Allocator> &t,
    const unsigned int /*file_version*/
){
    boost::serialization::stl::load_unordered_collection<
        Archive,
        boost::unordered_set<Key, HashFcn, EqualKey, Allocator>,
        boost::serialization::stl::archive_input_unordered_set<
            Archive,
            boost::unordered_set<Key, HashFcn, EqualKey, Allocator>
        >
    >(ar, t);
}

// split non-intrusive serialization function member into separate
// non intrusive save/load member functions
template<
    class Archive,
    class Key,
    class HashFcn,
    class EqualKey,
    class Allocator
>
inline void serialize(
    Archive & ar,
    boost::unordered_set<Key, HashFcn, EqualKey, Allocator> &t,
    const unsigned int file_version
){
    boost::serialization::split_free(ar, t, file_version);
}

// unordered_multiset
template<
    class Archive,
    class Key,
    class HashFcn,
    class EqualKey,
    class Allocator
>
inline void save(
    Archive & ar,
    const boost::unordered_multiset<Key, HashFcn, EqualKey, Allocator> &t,
    const unsigned int /*file_version*/
){
    boost::serialization::stl::save_unordered_collection<
        Archive,
        boost::unordered_multiset<Key, HashFcn, EqualKey, Allocator>
    >(ar, t);
}

template<
    class Archive,
    class Key,
    class HashFcn,
    class EqualKey,
    class Allocator
>
inline void load(
    Archive & ar,
    boost::unordered_multiset<Key, HashFcn, EqualKey, Allocator> &t,
    const unsigned int /*file_version*/
){
    boost::serialization::stl::load_unordered_collection<
        Archive,
        boost::unordered_multiset<Key, HashFcn, EqualKey, Allocator>,
        boost::serialization::stl::archive_input_unordered_multiset<
            Archive,
            boost::unordered_multiset<Key, HashFcn, EqualKey, Allocator>
        >
    >(ar, t);
}

// split non-intrusive serialization function member into separate
// non intrusive save/load member functions
template<
    class Archive,
    class Key,
    class HashFcn,
    class EqualKey,
    class Allocator
>
inline void serialize(
    Archive & ar,
    boost::unordered_multiset<Key, HashFcn, EqualKey, Allocator> &t,
    const unsigned int file_version
){
    boost::serialization::split_free(ar, t, file_version);
}

} // namespace serialization
} // namespace boost

#endif // BOOST_SERIALIZATION_BOOST_UNORDERED_SET_HPP


text:
bl_info = {
	"name": "Ogre Mesh Exporter",
	"description": "Exports mesh and (skeletal/morph/pose) animations to Ogre3D format.",
	"author": "Lih-Hern Pang",
	"version": (2,0,1),
	"blender": (2, 5, 7),
	"api": 31236,
	"location": "3D View Side Panel",
	"warning": '', # used for warning icon and text in addons panel
	"wiki_url": "http://www.ogre3d.org/tikiwiki/Blender+2.5+Exporter",
	"tracker_url": "http://sourceforge.net/tracker/?group_id=2997&atid=302997",
	"category": "Import-Export"}

if "bpy" in locals():
	import imp
	imp.reload(global_properties)
	imp.reload(material_properties)
	imp.reload(mesh_properties)
	imp.reload(main_exporter_panel)
	imp.reload(mesh_panel)
	imp.reload(mesh_exporter)
else:
	from . import global_properties
	from . import material_properties
	from . import mesh_properties
	from . import main_exporter_panel
	from . import mesh_panel
	from . import mesh_exporter

import bpy, pprint
from bpy.props import PointerProperty
from ogre_mesh_exporter.global_properties import GlobalProperties
from ogre_mesh_exporter.material_properties import MaterialProperties
from ogre_mesh_exporter.mesh_properties import MeshProperties

# registering and menu integration
def register():
	bpy.utils.register_module(__name__)

	# initialize the global properties group.
	bpy.types.Scene.ogre_mesh_exporter = PointerProperty(
		name = "Ogre Mesh Exporter properties",
		type = GlobalProperties,
		description = "Ogre Mesh Exporter properties"
	)

	bpy.types.Material.ogre_mesh_exporter = PointerProperty(
		name = "Ogre Mesh Exporter properties",
		type = MaterialProperties,
		description = "Ogre Mesh Exporter properties"
	)

	bpy.types.Mesh.ogre_mesh_exporter = PointerProperty(
		name = "Ogre Mesh Exporter properties",
		type = MeshProperties,
		description = "Ogre Mesh Exporter properties"
	)

# unregistering and removing menus
def unregister():
	bpy.utils.unregister_module(__name__)

if __name__ == "__main__":
	register()


text:
#ifndef __itkInterpolateImageFilter_h
#define __itkInterpolateImageFilter_h

#include "itkImageToImageFilter.h"
#include "itkLinearInterpolateImageFunction.h"

namespace itk
{
/** \class InterpolateImageFilter
 * \brief Interpolate an image from two N-D images.
 *
 * Interpolates an image from two input images of the same type
 * and same dimension (N). In particular, this filter forms an intermediate
 * (N+1)D image by concatenating the two input images and interpolating
 * an image a distance \f$ d \in [0,1] \f$ away from the first image.
 *
 * The interpolation is delegated to a user specified InterpolateImageFunction.
 * By default, linear interpolation is used.
 *
 * The filter is templated over the input image type and output image type.
 * It assumes that the input and output have the same number of dimensions.
 *
 * \ingroup MultiThreaded
 * \ingroup ITKImageGrid
 */
template< class TInputImage, class TOutputImage >
class ITK_EXPORT InterpolateImageFilter:
  public ImageToImageFilter< TInputImage, TOutputImage >
{
public:
  /** Standard class typedefs. */
  typedef InterpolateImageFilter                          Self;
  typedef ImageToImageFilter< TInputImage, TOutputImage > Superclass;
  typedef SmartPointer< Self >                            Pointer;
  typedef SmartPointer< const Self >                      ConstPointer;

  /** Method for creation through the object factory. */
  itkNewMacro(Self);

  /** Run-time type information (and related methods). */
  itkTypeMacro(InterpolateImageFilter, ImageToImageFilter);

  /** Inherit typedefs from Superclass */
  typedef typename Superclass::InputImageType        InputImageType;
  typedef typename Superclass::InputImagePointer     InputImagePointer;
  typedef typename Superclass::OutputImageType       OutputImageType;
  typedef typename Superclass::OutputImagePointer    OutputImagePointer;
  typedef typename Superclass::OutputImageRegionType OutputImageRegionType;

  /** Number of dimensions. */
  itkStaticConstMacro(ImageDimension, unsigned int,
                      TOutputImage::ImageDimension);
  itkStaticConstMacro(IntermediateImageDimension, unsigned int,
                      TOutputImage::ImageDimension + 1);

  /** Interpolator typedef. */
  typedef typename TInputImage::PixelType                                             InputPixelType;
  typedef Image< InputPixelType, itkGetStaticConstMacro(IntermediateImageDimension) > IntermediateImageType;
  typedef InterpolateImageFunction< IntermediateImageType >                           InterpolatorType;

  /** Set/Get the first image */
  void SetInput1(const InputImageType *image)
  { this->SetInput(image); }
  const InputImageType * GetInput1()
  { return this->GetInput(); }

  /** Set/Get the second image */
  void SetInput2(const InputImageType *image);

  const InputImageType * GetInput2();

  /** Set/Get the distance from the first image from which to generate
   * interpolated image. The default value is 0.5 */
  itkSetClampMacro(Distance, double, 0.0, 1.0);
  itkGetConstMacro(Distance, double);

  /** Set the interpolator function */
  itkSetObjectMacro(Interpolator, InterpolatorType)

  /** Get a pointer to the interpolator function. */
  itkGetObjectMacro(Interpolator, InterpolatorType);

  /** This method is used to set the state of the filter before
   * multi-threading. */
  void BeforeThreadedGenerateData();

  /** This method is used to run after multi-threading. */
  void AfterThreadedGenerateData();

#ifdef ITK_USE_CONCEPT_CHECKING
  /** Begin concept checking */
  itkConceptMacro( InputHasNumericTraitsCheck,
                   ( Concept::HasNumericTraits< InputPixelType > ) );
  /** End concept checking */
#endif
protected:
  InterpolateImageFilter();
  ~InterpolateImageFilter() {}
  void PrintSelf(std::ostream & os, Indent indent) const;

  /** InterpolateImageFilter can be implemented as a multithreaded filter. */
  void ThreadedGenerateData(const OutputImageRegionType & outputRegionForThread,
                            ThreadIdType threadId);

private:
  InterpolateImageFilter(const Self &); //purposely not implemented
  void operator=(const Self &);         //purposely not implemented

  typename InterpolatorType::Pointer m_Interpolator;

  typename IntermediateImageType::Pointer m_IntermediateImage;

  double m_Distance;
};
} // end namespace itk

#ifndef ITK_MANUAL_INSTANTIATION
#include "itkInterpolateImageFilter.hxx"
#endif

#endif


text:
from pyparsing import *

from ..constants.punctuation.deff import SLASH, LBRACKET, RBRACKET, EOL
from ..constants.math.deff import PLUS, MINUS, NUM, XVAR, FULLNUM
from ..entities.articles.deff import change, amount

from decl import *

ptmod << change + SLASH + change
loyaltymod << (LBRACKET + change + RBRACKET)

loyaltystart << amount
ptstart << (amount + SLASH + amount)