text:
package com.vmware.vim25.mo.samples.cluster;

import java.net.MalformedURLException;
import java.net.URL;

import com.vmware.vim25.ManagedObjectReference;
import com.vmware.vim25.ResourceAllocationInfo;
import com.vmware.vim25.SharesInfo;
import com.vmware.vim25.SharesLevel;
import com.vmware.vim25.VirtualMachineConfigSpec;
import com.vmware.vim25.mo.ServiceInstance;
import com.vmware.vim25.mo.VirtualMachine;
import com.vmware.vim25.mo.util.*;

/**
 * @author Steve Jin
 * http://vijava.sf.net
 * This sample code illustrates how to set up VM shares.
 * Please note that this sample is not intended to be complete or for production use.
 * Some of the information are hard-coded to simplify the code.
 */

public class DrsVmShares
{
  public static void main(String[] args) throws Exception
  {
    if(args.length!=3)
    {
      System.out.println("Usage: DrsVmShares url username password");
      System.exit(-1);
    }

    URL url = null;
    try
    {
      url = new URL(args[0]);
    } catch ( MalformedURLException urlE)
    {
      System.out.println("The URL provided is NOT valid. Please check it.");
      System.exit(-1);
    }
    String username = args[1];
    String password = args[2];
    String vm1_oid = "vm-26"; // The reference ID for VM 1
    String vm2_oid = "vm-28"; // The reference ID for VM 2

    // initialize the system, set up web services
    ServiceInstance si = new ServiceInstance(url, username, password, true);

    // create a new VirtualMachineConfigSpec for VM1
    VirtualMachineConfigSpec vmcs1 = new VirtualMachineConfigSpec();
    ResourceAllocationInfo rai1 = new ResourceAllocationInfo();
    SharesInfo si1 = new SharesInfo();
    si1.setLevel(SharesLevel.custom);
    si1.setShares(1333);
    rai1.setShares(si1);
    vmcs1.setCpuAllocation(rai1);

    // do the same for VM2
    VirtualMachineConfigSpec vmcs2 = new VirtualMachineConfigSpec();
    ResourceAllocationInfo rai2 = new ResourceAllocationInfo();
    SharesInfo si2 = new SharesInfo();
    si2.setLevel(SharesLevel.high);
    rai2.setShares(si2);
    vmcs2.setCpuAllocation(rai2);

    ManagedObjectReference vm1_mor = createMOR("VirtualMachine", vm1_oid);
    ManagedObjectReference vm2_mor = createMOR("VirtualMachine", vm2_oid);
    VirtualMachine vm1 = (VirtualMachine) MorUtil.createExactManagedEntity(si.getServerConnection(), vm1_mor);
    VirtualMachine vm2 = (VirtualMachine) MorUtil.createExactManagedEntity(si.getServerConnection(), vm2_mor);

    // make a web service call to set the configuration.
    vm1.reconfigVM_Task(vmcs1);
    vm2.reconfigVM_Task(vmcs2);

    // log out from web service
    si.getServerConnection().logout();
    System.out.println("Done with setting VM CPU shares.");
  }

  public static ManagedObjectReference createMOR(String type, String id)
  {
    ManagedObjectReference mor = new ManagedObjectReference();
    mor.setType(type);
    mor.set_value(id);
    return mor;
  }
}


text:
package test

import (
	"fmt"
	"net/http"
	"strings"
	"testing"

	"github.com/googleapis/gnostic/plugins/gnostic-go-generator/examples/v3.0/bookstore/bookstore"
)

const service = "http://localhost:8080"

//const service = "http://generated-bookstore.appspot.com"

func TestBookstore(t *testing.T) {
	// create a client
	b := bookstore.NewClient(service, nil)
	// reset the service by deleting all shelves
	{
		err := b.DeleteShelves()
		if err != nil {
			t.Log("delete shelves failed")
			t.Fail()
		}
	}
	// verify that the service has no shelves
	{
		response, err := b.ListShelves()
		if err != nil {
			t.Log("list shelves failed")
			t.Fail()
		}
		if (response == nil) || (response.OK == nil) || (response.OK.Shelves != nil) {
			t.Log(fmt.Sprintf("list shelves failed %+v", response.OK))
			t.Log(fmt.Sprintf("list shelves failed len=%d", len(response.OK.Shelves)))
			t.Fail()
		}
	}
	// attempting to get a shelf should return an error
	{
		response, err := b.GetShelf(1)
		if err == nil {
			t.Logf("get shelf failed to return an error (%+v)", response.OK)
			t.Fail()
		}
	}
	// attempting to get a book should return an error
	{
		response, err := b.GetBook(1, 2)
		if err == nil {
			t.Logf("get book failed to return an error (%+v)", response.OK)
			t.Fail()
		}
	}
	// add a shelf
	{
		var shelf bookstore.Shelf
		shelf.Theme = "mysteries"
		response, err := b.CreateShelf(shelf)
		if err != nil {
			t.Log("create shelf mysteries failed")
			t.Fail()
		}
		if (response.OK.Name != "shelves/1") ||
			(response.OK.Theme != "mysteries") {
			t.Log("create shelf mysteries failed")
			t.Fail()
		}
	}
	// add another shelf
	{
		var shelf bookstore.Shelf
		shelf.Theme = "comedies"
		response, err := b.CreateShelf(shelf)
		if err != nil {
			t.Log("create shelf comedies failed")
			t.Fail()
		}
		if (response.OK.Name != "shelves/2") ||
			(response.OK.Theme != "comedies") {
			t.Log("create shelf comedies failed")
			t.Fail()
		}
	}
	// get the first shelf that was added
	{
		response, err := b.GetShelf(1)
		if err != nil {
			t.Log("get shelf mysteries failed")
			t.Fail()
		}
		if (response.OK.Name != "shelves/1") ||
			(response.OK.Theme != "mysteries") {
			t.Log("get shelf mysteries failed")
			t.Fail()
		}
	}
	// list shelves and verify that there are 2
	{
		response, err := b.ListShelves()
		if err != nil {
			t.Log("list shelves failed")
			t.Fail()
		}
		if len(response.OK.Shelves) != 2 {
			t.Log("list shelves failed")
			t.Fail()
		}
	}
	// delete a shelf
	{
		err := b.DeleteShelf(2)
		if err != nil {
			t.Log("delete shelf failed")
			t.Fail()
		}
	}
	// list shelves and verify that there is only 1
	{
		response, err := b.ListShelves()
		if err != nil {
			t.Log("list shelves failed")
			t.Fail()
		}
		if len(response.OK.Shelves) != 1 {
			t.Log("list shelves failed")
			t.Fail()
		}
	}
	// list books on a shelf, verify that there are none
	{
		response, err := b.ListBooks(1)
		if err != nil {
			t.Log("list books failed")
			t.Fail()
		}
		if len(response.OK.Books) != 0 {
			t.Log("list books failed")
			t.Fail()
		}
	}
	// create a book
	{
		var book bookstore.Book
		book.Author = "Agatha Christie"
		book.Title = "And Then There Were None"
		_, err := b.CreateBook(1, book)
		if err != nil {
			t.Log("create book failed")
			t.Fail()
		}
	}
	// create another book
	{
		var book bookstore.Book
		book.Author = "Agatha Christie"
		book.Title = "Murder on the Orient Express"
		_, err := b.CreateBook(1, book)
		if err != nil {
			t.Log("create book failed")
			t.Fail()
		}
	}
	// get the first book that was added
	{
		_, err := b.GetBook(1, 1)
		if err != nil {
			t.Log("get book failed")
			t.Fail()
		}
	}
	// list the books on a shelf and verify that there are 2
	{
		response, err := b.ListBooks(1)
		if err != nil {
			t.Log("list books failed")
			t.Fail()
		}
		if len(response.OK.Books) != 2 {
			t.Log("list books failed")
			t.Fail()
		}
	}
	// delete a book
	{
		err := b.DeleteBook(1, 2)
		if err != nil {
			t.Log("delete book failed")
			t.Fail()
		}
	}
	// list the books on a shelf and verify that is only 1
	{
		response, err := b.ListBooks(1)
		if err != nil {
			t.Log("list books failed")
			t.Fail()
		}
		if len(response.OK.Books) != 1 {
			t.Log("list books failed")
			t.Fail()
		}
	}
	// verify the handling of a badly-formed request
	{
		req, err := http.NewRequest("POST", service+"/shelves", strings.NewReader(""))
		if err != nil {
			t.Log("bad request failed")
			return
		}
		resp, err := http.DefaultClient.Do(req)
		if err != nil {
			return
		}
		// we expect a 400 (Bad Request) code
		if resp.StatusCode != 400 {
			t.Log("bad request failed")
			t.Fail()
		}
		return
	}
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.river.lookup.util;

import java.io.IOException;
import java.io.Serializable;
import java.util.Map;
import org.apache.river.api.io.AtomicSerial;
import org.apache.river.api.io.AtomicSerial.GetArg;

/**
 * An implementation of the java.util.Map.Entry interface that has
 * a serialized form consistent in all virtual machines. ConsistentMapEntry
 * instances are unmodifiable. The setValue mutator method
 * throws UnsupportedOperationException.  This class permits null
 * for values and keys.
 *
 *

 * Although instances of this class are unmodifiable, they are not necessarily
 * immutable. If a client retrieves a mutable object (either a key or value) contained in a
 * ConsistentMapEntry and mutates that object, the client in effect
 * mutates the state of the ConsistentMapEntry. In this case, the
 * serialized form of the ConsistentMapEntry will most likely also
 * have been mutated. A ConsistentMapEntry that contains only immutable
 * objects will maintain a consistent serialized form indefinitely. But a
 * ConsistentMapEntry that contains mutable objects will maintain a
 * consistent serialized form only so long as the mutable objects are not
 * mutated.
 *
 * @author Bill Venners
 */
@AtomicSerial
final class ConsistentMapEntry<K,V> implements Map.Entry<K,V>, Serializable {

    private static final long serialVersionUID = -8633627011729114409L;

    /**
     * @serial An Object key, or null
     */
    private final K key;

    /**
     * @serial An Object value, or null
     */
    private final V value;

    /**
     * {@link AtomicSerial} constructor.
     * @param arg
     * @throws IOException
     * @throws ClassCastException if types don't match <K,V>
     */
    public ConsistentMapEntry(GetArg arg) throws IOException {
	this((K) arg.get("key", null), (V) arg.get("value", null));
    }

    /**
     * Constructs a new ConsistentMapEntry with passed
     * key and value. null is
     * allowed in either (or both) parameters.
     *
     * @param key the key (null key is OK)
     * @param value the value (null value is OK) associated with the key
     */
    public ConsistentMapEntry(K key, V value) {

        this.key = key;
        this.value = value;
    }

    /**
     * Returns the key.
     *
     * @return the key.
     */
    @Override
    public K getKey() {
        return key;
    }

    /**
     * Returns the value.
     *
     * @return the value.
     */
    @Override
    public V getValue() {
        return value;
    }

    /**
     * Replaces the value corresponding to this entry with the specified value. Because
     * all instances of this class are unmodifiable, this method always throws
     * UnsupportedOperationException.
     *
     * @throws UnsupportedOperationException always
     */
    @Override
    public V setValue(V value) {
        throw new UnsupportedOperationException();
    }

    /**
     * Compares the specified object (the Object passed
     * in o) with this ConsistentMapEntry
     * object for equality. Returns true if the specified object
     * is not null, if the specified object's class is
     * ConsistentMapEntry, if the keys of this object and
     * the specified object are either both null or semantically
     * equal, and the values of this object and the specified object are either
     * both null or semantically equal.
     *
     * @param o the object to compare against
     * @return true if the objects are the semantically equal,
     *     false otherwise.
     */
    @Override
    public boolean equals(Object o) {

        if (o == null) {
            return false;
        }

        if (o == this) {
            return true;
        }

        // TODO: ASK JOSH SHOULD EQUALS CHECK FOR INSTANCEOF OR EXACT CLASS?
        if (o.getClass() != ConsistentMapEntry.class) {
            return false;
        }

        ConsistentMapEntry unmod = (ConsistentMapEntry) o;

        boolean keysEqual = equalsOrNull(key, unmod.key);
        boolean valsEqual = equalsOrNull(value, unmod.value);

        return keysEqual && valsEqual;
    }

    private static boolean equalsOrNull(Object o1, Object o2) {
        return (o1 == null ? o2 == null : o1.equals(o2));
    }

    /**
     * Returns the hash code value for this ConsistentMapEntry object.
     *
     * @return the hashcode for this object
     */
    @Override
    public int hashCode() {

        int keyHash = (key == null ? 0 : key.hashCode());
        int valueHash = (value == null ? 0 : value.hashCode());

        return keyHash ^ valueHash;
    }
}


text:
*Please note that this library is currently not functional. This document describes the minimum feature set needed for release.*

## Using Daft

Daft is an automation tool for creating custom builds and deployments quickly and repeatably.

After you create a build.daft file in the root of your project, a simple

    docker run daft

will run your automation to completion. Note that you will of course need to have docker installed.

If you use the standard daft header in your build.daft, then you can simply run

    ./build.daft

to run your build.

Using labels allows you to stop the build earlier, so for instance

    ./build.daft compile

will stop the build after finishing the compile phase. You're free to define phases as you please, but they must execute in order.

## What is a daft script

Daft is actually a scripting language for Docker containers. A Daft script file is separated into 3 sections: the script, the data, and the rest. The rest is ignored by the interpreter, while the data is interpreted as a standard yaml document.

The script is a series of steps grouped into phases. The steps are executed in order until the interpreter encounters an error, or the steps in the specified phase are completed. There are only two kinds of steps, shell commands and Docker commands. A shell command is a bash command line, while a Docker command is a custom expression for daft.

A Docker command has three parts: the docker image, the path mapping and the command line arguments. The interpreter will fetch the docker image, infer the correct docker command line arguments for the path mapping and then start the docker container. The interpreter will wait for the docker execution to finish and, if successful, will then proceed with the next step.

## Daft script syntax

The three sections of a daft script are separated by three or more hyphens (---). Note that the sections are split before any other processing begins on the script, therefore three or more hyphens are not allowed for any other reason in the file, even in a string literal.

In the script portion of the file, comments are important for understanding intent. There are line and block comments

    # This is a line comment. It begins with a hash (#) anywhere on the line, and ends at the end of the line.

    #!
       A shebang (#!) starts a block comment.
       It can go for several lines.
       A block comment is explicitly closed by a bang-hash (! followed by #).
    !#

It might seem weird at first to use #!...!# as the block comment syntax, but it will become clear when we get to the
standard daft header below.

Aside from the comments, the scripts are mostly a series of steps. for instance a script could look like

    autoconf
    ./configure
    make

This probably won't do what you'd expect however. This script intends to run three separate docker containers built from images named "autoconf", "./configure", and "make" using their default locations and command line arguments. This is almost certainly not correct. If instead the script were

    > autoconf
    > ./configure
    > make

Then it might be a little bit closer to what you'd expect. Starting a line with a greater-than (>) tells the script
interpreter to treat the rest of the line as a literal shell command. The downside here of course is that you need
to have autoconf installed on your machine, and there's no telling whether that's true. Daft is completely portable,
if you use it correctly.

Most steps will be a Docker command instead of a shell command. A docker command is written as the docker image,
followed by a json path identifier into the yaml data object, followed by commandline arguments that should be passed
to the Docker command container. For instance

    daft/mvn childProject.root -X compile

Asks the daft script interpreter to run the Docker image called "daft-maven" against the path mappings identified in the yaml under the key "childProject.root" and to pass "-X compile" to the docker container on startup. Just for completeness, here's the full script with the data section

    daft/mvn childProject.root -X compile
    ---
    childProject:
      root:
        "/project": children/maven-project

what this means is that the "daft/mvn" image (which doesn't exist, by the way), has been configured to run against
a maven project in "/project". The actual execution within the interpreter for the previous example might look like.

    docker run daft/mvn -v /project:children/maven-project -X compile

Phases within the script are marked by labels

    aLabel:

A phase includes all the steps to the next label, so for instance

    compile:
    javac ...
    package:
    jar ...

In this example, the compile phase includes one command (javac). Sometimes you'll need to refer to a repository, for instance

    docker.fuwjax.com/daft-metalsmith web.src

If it gets too frustrating to type out the full image path, then path aliases are allowed.

    alias metalsmith docker.fuwjax.com/daft-metalsmith
    metalsmith web.src

Inline json is acceptable if you don't want to use the data lookup. That means it's legal to use

    metalsmith {"/project": "children/first"}

Of if you just want to use all the defaults

    metalsmith {}

In the command line arguments, shell commands or yaml data, it is acceptable to use environment variables. So for instance
if there is an environment variable called VERSION

    > touch v${VERSION}.txt
    metalsmith project $VERSION
    ---
    project:
      /target: build/$VERSION

Variables can even reference yaml properties.


text:
@implementation RSDiscoverModel

+ (NSArray *)demoData {
    RSDiscoverModel *model1 = [RSDiscoverModel new];
    model1.leftImageName = @"ff_IconShowAlbum";
    model1.leftText = @"朋友圈";
    model1.rightImageName = nil;
    RSDiscoverModel *model2 = [RSDiscoverModel new];
    model2.leftImageName = @"ff_IconQRCode";
    model2.leftText = @"扫一扫";
    model2.rightImageName = nil;
    RSDiscoverModel *model3 = [RSDiscoverModel new];
    model3.leftImageName = @"ff_IconShake";
    model3.leftText = @"摇一摇";
    model3.rightImageName = nil;
    RSDiscoverModel *model4 = [RSDiscoverModel new];
    model4.leftImageName = @"ff_IconLocationService";
    model4.leftText = @"附近的人";
    model4.rightImageName = @"FootStep";
    RSDiscoverModel *model5 = [RSDiscoverModel new];
    model5.leftImageName = @"ff_IconBottle";
    model5.leftText = @"漂流瓶";
    model5.rightImageName = nil;
    RSDiscoverModel *model6 = [RSDiscoverModel new];
    model6.leftImageName = @"CreditCard_ShoppingBag";
    model6.leftText = @"购物";
    model6.rightText = @"京东11.11";
    model6.rightImageName = @"AlbumNewNotify";
    RSDiscoverModel *model7 = [RSDiscoverModel new];
    model7.leftImageName = @"MoreGame";
    model7.leftText = @"游戏";
    model7.rightImageName = nil;

    return @[model1, model2, model3, model4, model5, model6, model7];
}

@end


text:
package com.images3.core.models.imageplant;

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

import com.images3.core.ImagePlant;
import com.images3.core.ImagePlantRepository;
import com.images3.data.ImagePlantOS;
import com.images3.data.spi.ImagePlantAccess;
import com.images3.exceptions.NoSuchEntityFoundException;

import org.gogoup.dddutils.pagination.AutoPaginatedResultDelegate;
import org.gogoup.dddutils.pagination.PaginatedResult;

public class ImagePlantRepositoryService extends AutoPaginatedResultDelegate<List<ImagePlant>> implements ImagePlantRepository  {

    private ImagePlantAccess imagePlantAccess;
    private ImagePlantFactoryService imagePlantFactory;
    private ImageRepositoryService imageRepository;
    private TemplateRepositoryService templateRepository;

    public ImagePlantRepositoryService(ImagePlantAccess imagePlantAccess,
            ImagePlantFactoryService imagePlantFactory,
            ImageRepositoryService imageRepository,
            TemplateRepositoryService templateRepository) {
        super(0, "getAllImagePlants");
        this.imagePlantAccess = imagePlantAccess;
        this.imagePlantFactory = imagePlantFactory;
        this.imageRepository = imageRepository;
        this.templateRepository = templateRepository;
    }

    @Override
    public ImagePlant storeImagePlant(ImagePlant imagePlant) {
        ImagePlantRoot root = (ImagePlantRoot) imagePlant;
        checkIfVoid(root);
        ImagePlantOS objectSegment = root.getObjectSegment();
        if (root.isNew()) {
            imagePlantAccess.insertImagePlant(objectSegment);

        } else if (root.isDirty()) {
            imagePlantAccess.updateImagePlant(objectSegment);
        }
        processTemplates(root);
        processImages(root);
        root.cleanMarks();
        return imagePlantFactory.reconstituteImagePlant(
                objectSegment, imageRepository, templateRepository);
    }

    private void processTemplates(ImagePlantRoot imagePlant) {
        List<TemplateEntity> templates = imagePlant.getDirtyTemplates();
        for (TemplateEntity template: templates) {
            if (!template.isVoid()) {
                templateRepository.storeTemplate(template);
            } else {
                templateRepository.removeTemplate(template);
            }

        }
    }

    private void processImages(ImagePlantRoot imagePlant) {
        List<ImageEntity> images = imagePlant.getDirtyImages();
        for (ImageEntity image: images) {
            if (!image.isVoid()) {
                imageRepository.storeImage(image);
            } else {
                imageRepository.removeImage(image);
            }
        }
    }

    @Override
    public void removeImagePlant(ImagePlant imagePlant) {
        ImagePlantRoot root = (ImagePlantRoot) imagePlant;
        checkIfVoid(root);
        ImagePlantOS objectSegment = root.getObjectSegment();
        imagePlantAccess.deleteImagePlant(objectSegment);
        root.markAsVoid();
        templateRepository.removeTemplates(root);
        imageRepository.removeImages(root);
    }

    @Override
    public ImagePlant findImagePlantById(String id) {
        ImagePlantOS objectSegment = imagePlantAccess.selectImagePlantById(id);
        ImagePlant entity = imagePlantFactory.reconstituteImagePlant(
                objectSegment, imageRepository, templateRepository);
        if (null == entity) {
            throw new NoSuchEntityFoundException("ImagePlant", id, "No such ImagePlant found.");
        }
        return entity;
    }

    @Override
    public PaginatedResult<List<ImagePlant>> findAllImagePlants() {
        PaginatedResult<List<ImagePlantOS>> osResult = imagePlantAccess.selectAllImagePlants();
        return new PaginatedResult<List<ImagePlant>>(
                this, "getAllImagePlants", new Object[] {osResult});
    }

    private List<ImagePlant> getAllImagePlants(List<ImagePlantOS> objectSegments) {
        List<ImagePlant> imagePlants = new ArrayList<ImagePlant>(objectSegments.size());
        for (ImagePlantOS os: objectSegments) {
            imagePlants.add(imagePlantFactory.reconstituteImagePlant(
                    os, imageRepository, templateRepository));
        }
        return imagePlants;
    }

    private void checkIfVoid(ImagePlantRoot imagePlant) {
        if (imagePlant.isVoid()) {
            throw new IllegalStateException(imagePlant.toString());
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<ImagePlant> fetchResult(String tag, Object[] arguments,
            Object pageCursor) {
        if ("getAllImagePlants".equals(tag)) {
            PaginatedResult<List<ImagePlantOS>> osResult = (PaginatedResult<List<ImagePlantOS>>) arguments[0];
            List<ImagePlantOS> objectSegments = osResult.getResult(pageCursor);
            return getAllImagePlants(objectSegments);
        }
        throw new UnsupportedOperationException(tag);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<ImagePlant> fetchAllResults(String tag, Object[] arguments) {
        if ("getAllImagePlants".equals(tag)) {
            PaginatedResult<List<ImagePlantOS>> osResult = (PaginatedResult<List<ImagePlantOS>>) arguments[0];
            List<ImagePlantOS> objectSegments = osResult.getAllResults();
            return getAllImagePlants(objectSegments);
        }
        throw new UnsupportedOperationException(tag);
    }

}


text:
/*****************************************************************************

  fir_fsm.cpp --

  Original Author: Rocco Jonack, Synopsys, Inc.

 *****************************************************************************/

/*****************************************************************************

  MODIFICATION LOG - modifiers, enter your name, affiliation, date and
  changes you are making here.

      Name, Affiliation, Date:
  Description of Modification:

 *****************************************************************************/

#include <systemc.h>
#include "fir_fsm.h"

void fir_fsm::entry() {

  sc_uint<3> state_tmp;

  // reset behavior
  if(! reset.read()) {
    state = reset_s;
    state_tmp = 0;
    state_out.write((unsigned)state_tmp);
  } else {
#ifdef DEBUG
    cout << "debug: " << state << " " << state_tmp << " " << reset.read() << endl;
#endif
    // main state machine
    switch(state) {
    case reset_s:
      state = first_s;
      state_tmp = 0;
      state_out.write((unsigned)state_tmp);
      break;
    case first_s:
      if(in_valid.read()==true) {
	state = second_s;
      };
      state_tmp = 1;
      state_out.write((unsigned)state_tmp);
      break;
    case second_s:
      state = third_s;
      state_tmp = 2;
      state_out.write((unsigned)state_tmp);
      break;
    case third_s:
      state = output_s;
      state_tmp = 3;
      state_out.write((unsigned)state_tmp);
      break;
    default:
      state = first_s;
      state_tmp = 4;
      state_out.write((unsigned)state_tmp);
      break;
    }
  }
}


text:
extern GLFWwindow *window;

int main () {
	switch(pt_app_initialize()) {
        case PT_INIT_GLFW_FAILURE:
            exit(EXIT_FAILURE);

        case PT_INIT_SUCCESS:
            break;
    }

    while (!glfwWindowShouldClose(window)) {
		pt_app_main_loop();
    }

    glfwDestroyWindow(window);
    glfwTerminate();
    exit(EXIT_SUCCESS);
}

#endif // _WIN32


text:
add_library(wil INTERFACE)
target_include_directories(wil INTERFACE external/wil/include/)


text:
_this plugin is being developed as part of some articles I'm writing on [JavaScriptPlayground](http://www.javascriptplayground.com). It's not finished yet_

---
# jQuery Pullquote

A jQuery plugin to pull out quotes into new elements for styling on the page.

## Getting Started
Download the [production version][min] or the [development version][max].

[min]: https://raw.github.com/jackfranklin/jquery.pullquote/master/dist/jquery.pullquote.min.js
[max]: https://raw.github.com/jackfranklin/jquery.pullquote/master/dist/jquery.pullquote.js

In your web page:

```html
<script src="jquery.js"></script>
<script src="dist/jquery.pullquote.min.js"></script>
<script>
jQuery(function($) {
  $("p span").pullQuote({
    outputClass: "pullquote",
    outputElem: "blockquote",
    insertAfter: "elem"
  });
});
</script>
```

Changing those options as needed. PullQuote will then take the text within the selector, and create a new element after `insertAfter` with that text within.

## Documentation
_(Coming soon)_

## Examples
_(Coming soon)_

## Contributing
In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using [grunt](https://github.com/cowboy/grunt). Make sure all tests pass before making a pull request.

_Also, please don't edit files in the "dist" subdirectory as they are generated via grunt. You'll find source code in the "src" subdirectory!_

## Release History
27th April: 0.1.0

## License
Copyright (c) 2012 Jack Franklin
Licensed under the MIT, GPL licenses.


text:
<!DOCTYPE html>
<html lang="{{ trans('language.code') }}">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        {!! SEO::generate() !!}

        <!-- Styles -->
        <link href="{{ mix('css/app.css') }}" rel="stylesheet">

        <!-- Fonts -->
        <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,700&subset=latin-ext" rel="stylesheet">
    </head>
    <body>
        <div id="app">
            <!-- Navbar -->
            @include('components.navbar')

            <!-- Content -->
            @yield('content')

            <!-- Footer -->
            @include('components.footer')
        </div>

        <!-- Script -->
        <script src="{{ mix('js/app.js') }}"></script>
        @yield('body')
    </body>
</html>


text:
package nack

import "errors"

// ErrInvalidSize is returned by newReceiveLog/newSendBuffer, when an incorrect buffer size is supplied.
var ErrInvalidSize = errors.New("invalid buffer size")

var (
	errPacketReleased          = errors.New("could not retain packet, already released")
	errFailedToCastHeaderPool  = errors.New("could not access header pool, failed cast")
	errFailedToCastPayloadPool = errors.New("could not access payload pool, failed cast")
)


text:
'use strict';

var RCTUIManager = require('NativeModules').UIManager;
var UnimplementedView = require('UnimplementedView');

var createReactIOSNativeComponentClass = require('createReactIOSNativeComponentClass');
var deepDiffer = require('deepDiffer');
var insetsDiffer = require('insetsDiffer');
var pointsDiffer = require('pointsDiffer');
var matricesDiffer = require('matricesDiffer');
var sizesDiffer = require('sizesDiffer');
var verifyPropTypes = require('verifyPropTypes');

/**
 * Used to create React components that directly wrap native component
 * implementations.  Config information is extracted from data exported from the
 * RCTUIManager module.  You should also wrap the native component in a
 * hand-written component with full propTypes definitions and other
 * documentation - pass the hand-written component in as `wrapperComponent` to
 * verify all the native props are documented via `propTypes`.
 *
 * If some native props shouldn't be exposed in the wrapper interface, you can
 * pass null for `wrapperComponent` and call `verifyPropTypes` directly
 * with `nativePropsToIgnore`;
 *
 * Common types are lined up with the appropriate prop differs with
 * `TypeToDifferMap`.  Non-scalar types not in the map default to `deepDiffer`.
 */
function requireNativeComponent(
  viewName: string,
  wrapperComponent: ?Function
): Function {
  var viewConfig = RCTUIManager.viewConfigs && RCTUIManager.viewConfigs[viewName];
  if (!viewConfig) {
    return UnimplementedView;
  }
  var nativeProps = {
    ...RCTUIManager.viewConfigs.RCTView.nativeProps,
    ...viewConfig.nativeProps,
  };
  viewConfig.validAttributes = {};
  for (var key in nativeProps) {
    // TODO: deep diff by default in diffRawProperties instead of setting it here
    var differ = TypeToDifferMap[nativeProps[key].type] || deepDiffer;
    viewConfig.validAttributes[key] = {diff: differ};
  }
  if (__DEV__) {
    wrapperComponent && verifyPropTypes(wrapperComponent, viewConfig);
  }
  return createReactIOSNativeComponentClass(viewConfig);
}

var TypeToDifferMap = {
  // iOS Types
  CATransform3D: matricesDiffer,
  CGPoint: pointsDiffer,
  CGSize: sizesDiffer,
  UIEdgeInsets: insetsDiffer,
  // Android Types
  // (not yet implemented)
};

module.exports = requireNativeComponent;


text:
package org.apache.drill.exec.impersonation.hive;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.apache.calcite.schema.Schema.TableType;
import org.apache.drill.exec.hive.HiveTestUtilities;
import org.apache.drill.exec.impersonation.BaseTestImpersonation;
import org.apache.drill.exec.store.hive.HiveStoragePluginConfig;
import org.apache.drill.test.TestBuilder;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.conf.HiveConf.ConfVars;
import org.apache.hadoop.hive.metastore.MetaStoreUtils;
import org.apache.hadoop.hive.ql.Driver;
import org.apache.hadoop.hive.shims.ShimLoader;
import org.junit.BeforeClass;

import static org.apache.drill.exec.hive.HiveTestUtilities.createDirWithPosixPermissions;
import static org.apache.drill.exec.hive.HiveTestUtilities.executeQuery;
import static org.apache.hadoop.fs.FileSystem.FS_DEFAULT_NAME_KEY;
import static org.apache.hadoop.hive.conf.HiveConf.ConfVars.METASTOREURIS;

public class BaseTestHiveImpersonation extends BaseTestImpersonation {
  protected static final String hivePluginName = "hive";

  protected static HiveConf hiveConf;
  protected static String whDir;

  protected static String studentData;
  protected static String voterData;

  protected static final String studentDef = "CREATE TABLE %s.%s" +
      "(rownum int, name string, age int, gpa float, studentnum bigint) " +
      "ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' STORED AS TEXTFILE";

  protected static final String voterDef = "CREATE TABLE %s.%s" +
      "(voter_id int,name varchar(30), age tinyint, registration string, " +
      "contributions double,voterzone smallint,create_time timestamp) " +
      "ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' STORED AS TEXTFILE";

  protected static final String partitionStudentDef = "CREATE TABLE %s.%s" +
      "(rownum INT, name STRING, gpa FLOAT, studentnum BIGINT) " +
      "partitioned by (age INT) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' STORED AS TEXTFILE";

  @BeforeClass
  public static void setUp() {
    HiveTestUtilities.assumeJavaVersion();
  }

  protected static void prepHiveConfAndData() throws Exception {
    hiveConf = new HiveConf();

    File scratchDir = createDirWithPosixPermissions(dirTestWatcher.getRootDir(), "scratch_dir");
    File localScratchDir = createDirWithPosixPermissions(dirTestWatcher.getRootDir(), "local_scratch_dir");
    File metaStoreDBDir = new File(dirTestWatcher.getRootDir(), "metastore_db");

    // Configure metastore persistence db location on local filesystem
    final String dbUrl = String.format("jdbc:derby:;databaseName=%s;create=true",  metaStoreDBDir.getAbsolutePath());
    hiveConf.set(ConfVars.METASTORECONNECTURLKEY.varname, dbUrl);

    hiveConf.set(ConfVars.SCRATCHDIR.varname, "file://" + scratchDir.getAbsolutePath());
    hiveConf.set(ConfVars.LOCALSCRATCHDIR.varname, localScratchDir.getAbsolutePath());
    hiveConf.set(ConfVars.METASTORE_SCHEMA_VERIFICATION.varname, "false");
    hiveConf.set(ConfVars.METASTORE_AUTO_CREATE_ALL.varname, "true");
    hiveConf.set(ConfVars.HIVE_CBO_ENABLED.varname, "false");

    // Set MiniDFS conf in HiveConf
    hiveConf.set(FS_DEFAULT_NAME_KEY, dfsConf.get(FS_DEFAULT_NAME_KEY));

    whDir = hiveConf.get(ConfVars.METASTOREWAREHOUSE.varname);
    FileSystem.mkdirs(fs, new Path(whDir), new FsPermission((short) 0777));

    studentData = getPhysicalFileFromResource("student.txt");
    voterData = getPhysicalFileFromResource("voter.txt");
  }

  protected static void startHiveMetaStore() throws Exception {
    final int port = MetaStoreUtils.findFreePort();

    hiveConf.set(METASTOREURIS.varname, "thrift://localhost:" + port);

    MetaStoreUtils.startMetaStore(port, ShimLoader.getHadoopThriftAuthBridge(), hiveConf);
  }

  protected static HiveStoragePluginConfig createHiveStoragePlugin(final Map<String, String> hiveConfig) throws Exception {
    HiveStoragePluginConfig pluginConfig = new HiveStoragePluginConfig(hiveConfig);
    pluginConfig.setEnabled(true);
    return pluginConfig;
  }

  protected static Path getWhPathForHiveObject(final String dbName, final String tableName) {
    if (dbName == null) {
      return new Path(whDir);
    }

    if (tableName == null) {
      return new Path(whDir, dbName + ".db");
    }

    return new Path(new Path(whDir, dbName + ".db"), tableName);
  }

  protected static void addHiveStoragePlugin(final Map<String, String> hiveConfig) throws Exception {
    getDrillbitContext().getStorage().createOrUpdate(hivePluginName, createHiveStoragePlugin(hiveConfig), true);
  }

  protected void showTablesHelper(final String db, List<String> expectedTables) throws Exception {
    final String dbQualified = hivePluginName + "." + db;
    final TestBuilder testBuilder = testBuilder()
        .sqlQuery("SHOW TABLES IN " + dbQualified)
        .unOrdered()
        .baselineColumns("TABLE_SCHEMA", "TABLE_NAME");

    if (expectedTables.size() == 0) {
      testBuilder.expectsEmptyResultSet();
    } else {
      for (String tbl : expectedTables) {
        testBuilder.baselineValues(dbQualified, tbl);
      }
    }

    testBuilder.go();
  }

  protected void fromInfoSchemaHelper(final String db, List<String> expectedTables, List<TableType> expectedTableTypes) throws Exception {
    final String dbQualified = hivePluginName + "." + db;
    final TestBuilder testBuilder = testBuilder()
        .sqlQuery("SELECT TABLE_SCHEMA, TABLE_NAME, TABLE_TYPE \n" +
            "FROM INFORMATION_SCHEMA.`TABLES` \n" +
            "WHERE TABLE_SCHEMA = '" + dbQualified + "'")
        .unOrdered()
        .baselineColumns("TABLE_SCHEMA", "TABLE_NAME", "TABLE_TYPE");

    if (expectedTables.size() == 0) {
      testBuilder.expectsEmptyResultSet();
    } else {
      for (int i = 0; i < expectedTables.size(); ++i) {
        testBuilder.baselineValues(dbQualified, expectedTables.get(i), expectedTableTypes.get(i).toString());
      }
    }

    testBuilder.go();
  }

  public static void stopHiveMetaStore() throws Exception {
    // Unfortunately Hive metastore doesn't provide an API to shut it down. It will be exited as part of the test JVM
    // exit. As each metastore server instance is using its own resources and not sharing it with other metastore
    // server instances this should be ok.
  }

  static void queryView(String viewName) throws Exception {
    String query = String.format("SELECT rownum FROM %s.tmp.%s ORDER BY rownum LIMIT 1", MINI_DFS_STORAGE_PLUGIN_NAME, viewName);
    testBuilder()
        .sqlQuery(query)
        .unOrdered()
        .baselineColumns("rownum")
        .baselineValues(1)
        .go();
  }

  static void queryViewNotAuthorized(String viewName) throws Exception {
    String query = String.format("SELECT rownum FROM %s.tmp.%s ORDER BY rownum LIMIT 1", MINI_DFS_STORAGE_PLUGIN_NAME, viewName);
    errorMsgTestHelper(query, String.format(
        "Not authorized to read view [%s] in schema [%s.tmp]", viewName, MINI_DFS_STORAGE_PLUGIN_NAME));
  }

  static void createTableWithStoragePermissions(final Driver hiveDriver, final String db, final String tbl, final String tblDef,
                                                final String tblData, final String user, final String group, final short permissions) throws Exception {
    createTable(hiveDriver, db, tbl, tblDef, tblData);
    setStoragePermissions(db, tbl, user, group, permissions);
  }

  static void setStoragePermissions(String db, String tbl, String user, String group, short permissions) throws IOException {
    final Path p = getWhPathForHiveObject(db, tbl);
    fs.setPermission(p, new FsPermission(permissions));
    fs.setOwner(p, user, group);
  }

  static void createTable(final Driver driver, final String db, final String tbl, final String tblDef,
                          final String data) throws Exception {
    executeQuery(driver, String.format(tblDef, db, tbl));
    executeQuery(driver, String.format("LOAD DATA LOCAL INPATH '%s' INTO TABLE %s.%s", data, db, tbl));
  }

}


text:
<#if MID?if_exists == 'admin'>

설정

기본설정

</#if>


text:
define([
    'background/collection/clientErrors'
], function (ClientErrors) {
    'use strict';

    var ClientErrorManager = Backbone.Model.extend({
        defaults: function () {
            return {
                platformInfo: {
                    os: '',
                    arch: '',
                    nacl_arch: ''
                },
                reportedErrors: new ClientErrors()
            };
        },

        initialize: function () {
            chrome.runtime.getPlatformInfo(this._onChromeRuntimeGetPlatformInfo.bind(this));
            window.onerror = this._onWindowError.bind(this);
            this.listenTo(Streamus.channels.error.commands, 'log:error', this._logError);
            this.listenTo(Streamus.channels.error.vent, 'windowError', this._onWindowError);
        },

        //  Only log client errors to the database in a deploy environment, not when debugging locally.
        _warnDebugEnabled: function(message) {
            console.warn('Debugging enabled; Message:' + message);
        },

        _onChromeRuntimeGetPlatformInfo: function (platformInfo) {
            this.set('platformInfo', platformInfo);
        },

        _onWindowError: function (message, url, lineNumber, columnNumber, error) {
            this._createClientError(message, url, lineNumber, error);
        },

        _logError: function(error) {
            this._createClientError(error.message, '', 0, error);
        },

        _createClientError: function (message, url, lineNumber, error) {
            if (Streamus.localDebug && !Streamus.testing) {
                this._warnDebugEnabled(message);
                return;
            }

            this.get('reportedErrors').create({
                message: message,
                url: url,
                lineNumber: lineNumber,
                operatingSystem: this.get('platformInfo').os,
                architecture: this.get('platformInfo').arch,
                error: error
            });
        }
    });

    return ClientErrorManager;
});


text:
function ServerEngine(){
}
ServerEngine.prototype.name = function(){
  return 'null server engine';
};
ServerEngine.prototype.destroy = function(){
};
ServerEngine.prototype.beginBootstrap = function(meanioinstance, database){
};
ServerEngine.prototype.endBootstrap = function(callback){
};
ServerEngine.produceEngine = function(enginename){
  var engine;

  switch(enginename || 'express'){
    case 'express':
      engine = new (require('./ExpressEngine'))();
      break;
    default:
      throw 'Server Engine '+enginename+' not supported';
  }
  return engine;
};

module.exports = ServerEngine;


text:
require 'spec_helper'

describe KeywordFinder::Keywords do
  it 'behaves like an array hence' do
    a = KeywordFinder::Keywords.new(["a","b"])
    expect(a[0]).to eq("a");
    expect(a.last).to eq("b");
    a << "c"
    a << "d"
    expect(a[2]).to eq("c");
    expect(a.last).to eq("d");
    expect(a.class).to eq(KeywordFinder::Keywords);
  end
  describe "#combine_more_specifics" do
    it "should combine (a)b to ab" do
      a = KeywordFinder::Keywords.new()
      expect(a.combine_more_specifics("a(b)")).to eq("ab")
    end
    it "should combine anothe (a)b and b(a) to ..." do
      a = KeywordFinder::Keywords.new()
      expect(a.combine_more_specifics("anothe (a)b and b(a) to")).to eq("anothe ab and ba to")
    end
  end
  describe "#to_regex" do
    it "should return an empty regex if no keywords are present" do
      a = KeywordFinder::Keywords.new()
      expect(a.to_regex).to eq(/()/)
    end
    it "should return a filled regex when keywords are present" do
      a = KeywordFinder::Keywords.new(["a","b"])
      expect(a.to_regex).to eq(/(\sa\s|\sb\s)/)
    end
    it "should work with utf-8 characters" do
      a = KeywordFinder::Keywords.new(["ï","æ"])
      expect(a.to_regex).to eq(/(\sï\s|\sæ\s)/)
    end
    it "should work with keywords with brackets" do
      a = KeywordFinder::Keywords.new(["a","a (b)"])
      expect(a.to_regex).to eq(/(\sa\ \ \(b\)\s|\sa\s)/)
    end
    it "should work with reserved regex characters" do
      a = KeywordFinder::Keywords.new([" * "," ? ", " (hallo) ", " . ", " + "])
      expect(a.to_regex).to eq(/(\s\ \ \(hallo\)\ \ \s|\s\ \ \*\ \ \s|\s\ \ \?\ \ \s|\s\ \ \.\ \ \s|\s\ \ \+\ \ \s)/)
    end
    it "should work with reserved regex characters AND allow for the entire_words_only option to eq false" do
      a = KeywordFinder::Keywords.new([" * "," ? ", " (hallo) ", " . ", " + "])
      expect(a.to_regex({entire_words_only: false})).to eq(/(\ \ \(hallo\)\ \ |\ \ \*\ \ |\ \ \?\ \ |\ \ \.\ \ |\ \ \+\ \ )/)
    end
  end
  describe "#find_in" do
    it 'is implemented and returns [] when empty' do
      a = KeywordFinder::Keywords.new()
      expect(a.find_in("")).to eq([])
    end
    it 'accepts options' do
      a = KeywordFinder::Keywords.new()
      expect(a.find_in("", {})).to eq([])
    end
    it 'finds keywords in sentence' do
      a = KeywordFinder::Keywords.new(["a","b"])
      expect(a.find_in("another ape b")).to eq(["b"])
      expect(a.find_in("another a pe b")).to eq(["a","b"])
    end
    it 'finds keywords in sentence, while ignoring case' do
      a = KeywordFinder::Keywords.new(["a","b"])
      expect(a.find_in("another ape B")).to eq(["b"])
      expect(a.find_in("another A pe b")).to eq(["a","b"])
    end
    it 'finds keywords in more trashy sentence' do
      a = KeywordFinder::Keywords.new(["a","b"])
      expect(a.find_in("another ape. b?")).to eq(["b"])
      expect(a.find_in("another a. pe b?")).to eq(["a","b"])
    end
    it 'finds keywords in sentence with subsentences' do
      a = KeywordFinder::Keywords.new(["a","b"])
      expect(a.find_in("a (lees b)")).to eq(["a","b"])
    end
    it 'finds keywords with regex-escaped characters' do
      a = KeywordFinder::Keywords.new(["vlees*","[kaas]"])
      expect(a.find_in("vlees*, [kaas]")).to eq(["vlees*","[kaas]"])
    end
    it 'finds keywords in sentence with subsentences {options: strategy: none}' do
      a = KeywordFinder::Keywords.new(["a","b"])
      expect(a.find_in("a (lees b)", {subsentences_strategy: :none})).to eq(["a","b"])
    end
    it 'finds keywords in sentence with subsentences {options: strategy: :always_ignore}' do
      a = KeywordFinder::Keywords.new(["a","b"])
      expect(a.find_in("a (alternatief b)", {subsentences_strategy: :always_ignore})).to eq(["a"])
    end
    it 'finds keywords in sentence with subsentences {options: strategy: :ignore_if_found_in_main}' do
      a = KeywordFinder::Keywords.new(["a","b"])
      expect(a.find_in("a (alternatief b)", {subsentences_strategy: :ignore_if_found_in_main})).to eq(["a"])
      a = KeywordFinder::Keywords.new(["ab","b"])
      expect(a.find_in("a (alternatief b)", {subsentences_strategy: :ignore_if_found_in_main})).to eq(["b"])
    end
    it 'should try the longest first' do
      a = KeywordFinder::Keywords.new(["wild", "wild konijn"])
      expect(a.find_in("wild konijn")).to eq(["wild konijn"])
    end
    it 'should deal with brackets in start of sentence' do
      a = KeywordFinder::Keywords.new(["wild", "konijn"])
      expect(a.find_in("(wild) konijn en meer")).to eq(["konijn", "wild"])
    end
    it 'should deal with keywords with brackets' do
      a = KeywordFinder::Keywords.new(["wild", "konijn", "(wild) konijn"])
      expect(a.find_in("(wild) konijn en meer")).to eq(["(wild) konijn"])
    end
    it 'should respect the entire_words_only false setting if given' do
      a = KeywordFinder::Keywords.new(["wild", "konijn"])
      expect(a.find_in("wildkonijn", {entire_words_only: false})).to eq(["wild", "konijn"])
    end
    it 'should prefer the longest even if the entire_words_only false setting if given' do
      a = KeywordFinder::Keywords.new(["wild", "konijn", "wildkonijn"])
      expect(a.find_in("wildkonijn", {entire_words_only: false})).to eq(["wildkonijn"])
    end
    it 'should work even accross words when the entire_words_only false setting if given' do
      a = KeywordFinder::Keywords.new(["wild", "konijn", "wildkonijn", "gekonfijte sinaasappel"])
      expect(a.find_in("wildkonijn met gekonfijte sinaasappels", {entire_words_only: false})).to eq(["wildkonijn", "gekonfijte sinaasappel"])
    end
    it 'should work even accross words when the entire_words_only false setting if given' do
      a = KeywordFinder::Keywords.new(["wild", "konijn", "wildkonijn", "gekonfijte sinaasappel", "ui"])
      expect(a.find_in("wildkonijn met gekonfijte sinaasappels fruit", {entire_words_only: :when_short})).to eq(["wildkonijn", "gekonfijte sinaasappel"])
    end
    it 'should work with non-ascii characters' do
      a = KeywordFinder::Keywords.new(["orchideeën", "planten", "orchidaceae"])
      expect(a.find_in("De familie van de orchideeën (Orchidaceae) is een van de grootste plantenfamilies op aarde", {entire_words_only: :when_short})).to eq(["orchideeën", "planten", "orchidaceae"])
    end
    pending 'should work with non-ascii characters' do
      a = KeywordFinder::Keywords.new(["orchideeën", "planten", "orchidaceae"])
      expect(a.find_in("De familie van de orchideeen (Orchidaceae) is een van de grootste plantenfamilies op aarde", {entire_words_only: :when_short})).to eq(["orchideeën", "planten", "orchidaceae"])
    end
  end
  describe "#separate_main_and_sub_sentences" do
    it "should return empty string when empty string is given" do
      a = KeywordFinder::Keywords.new(["a","b"])
      expect(a.separate_main_and_sub_sentences("")).to eq({main:"",subs:[]})
    end
    it "should return sentence between brackets" do
      a = KeywordFinder::Keywords.new(["a","b"])
      expect(a.separate_main_and_sub_sentences("hallo (is dit wel een) zin")).to eq({main:"hallo  zin",subs:["is dit wel een"]})
    end
    it "should return this sentence between brackets" do
      a = KeywordFinder::Keywords.new(["a","b"])
      expect(a.separate_main_and_sub_sentences("(wild) konijn en meer")).to eq({main:"konijn en meer",subs:["wild"]})
    end
  end

  describe "#scan_part" do
    it 'should deal with keywords with brackets' do
      a = KeywordFinder::Keywords.new(["wild", "konijn", "(wild) konijn"])
      expect(a.scan_part("(wild) konijn en meer")).to eq(["(wild) konijn"])
    end
  end

  describe "#complex_test" do
    it "should work for these examples" do
      a = KeywordFinder::Keywords.new(["aardappelen", "zachtkokende aardappelen", "zout",
        "schimmelkaas", "kaas", "oude harde kaas", "kikkererwten", "maïs",
        "bruine bonen", "shiitake", "boter", "kidney bonen", "spinazie", "knoflook", "peterselie", "peper"])

      examples = {"een grote pan zachtkokende aardappelen met een snufje zout"=>["zachtkokende aardappelen", "zout"],
        "schimmelkaas" => ["schimmelkaas"],
        "(schimmel)kaas" => ["schimmelkaas"],
        "old amsterdam (maar een andere oude harde kaas kan natuurlijk ook)" => ["oude harde kaas"],
        "g (verse) shiitake in bitesize stukjes gesneden" => ["shiitake"],
        "pot hak bonenmix (kikkererwten, maïs, kidney en bruine bonen) afgespoeld en uitgelekt" => ["kikkererwten", "maïs", "bruine bonen"],
        "g boter gesmolten en licht afgekoeld" => ["boter"],
        "peterselie knoflook spinazie zout peper kaas" => ["peterselie", "knoflook", "spinazie", "zout", "peper", "kaas"],
        "peterselie knoflook
spinazie zout
peper shiitake" => ["peterselie", "knoflook", "spinazie", "zout", "peper", "shiitake"],
        "\n\t\t\t\n\t\t\t\t100 g Parmezaanse kaas (stukje)\t\t" => ["kaas"]
      }

      examples.each do |sentence, expected|
        expect( a.find_in(sentence) ).to eq(expected)
      end
    end
  end

end


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/menu_ok"
        android:icon="@drawable/ic_done_white_48dp"
        android:title="@string/btn_save"
        app:showAsAction="always|withText"/>
    <item
        android:id="@+id/menu_delete"
        android:icon="@android:drawable/ic_menu_delete"
        android:title="@string/action_visit_delete"/>
</menu>


text:
package net.siufung.bzgzpt.persistence.uap.service.impl;

import java.util.List;

import javax.annotation.Resource;

import net.siufung.bzgzpt.persistence.uap.dao.ISysTaskLogDao;
import net.siufung.bzgzpt.persistence.uap.domain.SysTaskLog;
import net.siufung.bzgzpt.persistence.uap.service.ISysTaskLogService;

import org.springframework.stereotype.Service;

import cn.jbinfo.platform.core.basic.exception.ServiceException;
/**
 * 对SysTaskLog实体进行CRUD操作
 */
@Service("sysTaskLogService")
public class SysTaskLogServiceImpl implements ISysTaskLogService{

	@Resource
	private ISysTaskLogDao sysTaskLogDao;
	@Override
	public void save(SysTaskLog sysTaskLog) {
		sysTaskLogDao.save(sysTaskLog);
	}
	@Override
	public void deleteById(Long id) {
		sysTaskLogDao.deleteById(id);
	}
	@Override
	public void update(SysTaskLog sysTaskLog) {
		sysTaskLogDao.update(sysTaskLog);
	}
	@Override
	public SysTaskLog getById(Long id) {
		return sysTaskLogDao.getById(id);
	}
	@Override
	public SysTaskLog getByModel(SysTaskLog sysTaskLog) {
		return sysTaskLogDao.getByModel(sysTaskLog);
	}
	@Override
	public List<SysTaskLog> searchList(SysTaskLog sysTaskLog) {
		return sysTaskLogDao.searchList(sysTaskLog);
	}
	/*public CommPager searchPager(SysTaskLog sysTaskLog,int pageNum,int pageSize) {
		PageHelper.startPage(pageNum,pageSize);
		List l = sysTaskLogDao.searchList(sysTaskLog);
		return new CommPager(l);
	}*/
	@Override
	public SysTaskLog get(SysTaskLog paramT) throws ServiceException {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public SysTaskLog getById(String id) throws ServiceException {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public List<SysTaskLog> findList(SysTaskLog paramT) throws ServiceException {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public void insert(SysTaskLog paramT) throws ServiceException {
		// TODO Auto-generated method stub

	}
	@Override
	public void delete(SysTaskLog paramT) throws ServiceException {
		// TODO Auto-generated method stub

	}
	@Override
	public void save(String taskType, String message) {
		SysTaskLog tl = new SysTaskLog();
		tl.setTaskType(taskType);
		tl.setMessage(message);
		this.sysTaskLogDao.save(tl);
	}
}


text:
// Add all states here
// Example:
// game.state.add('Menu', Menu);
// game.state.start('Menu');


text:
DROP TABLE IF EXISTS measurements;
DROP TABLE IF EXISTS sensors CASCADE;
DROP TABLE IF EXISTS outputs CASCADE;
DROP TABLE IF EXISTS places;
DROP TYPE IF EXISTS client_status;
DROP TYPE IF EXISTS signal_status;
DROP TABLE IF EXISTS lifecycle;


text:
// -*- C++ -*-

//=============================================================================
/**
 *  @file    Topology_Loader.h
 *
 *  $Id: Topology_Loader.h 14 2007-02-01 15:49:12Z mitza $
 *
 *  @author Jonathan Pollack <pollack_j@ociweb.com>
 */
//=============================================================================

#ifndef TOPOLOGY_LOADER_H
#define TOPOLOGY_LOADER_H
#include /**/ "ace/pre.h"

#include "orbsvcs/Notify/notify_serv_export.h"

#include "ace/config-all.h"

#if !defined (ACE_LACKS_PRAGMA_ONCE)
#pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */

#include "tao/Versioned_Namespace.h"
#include "ace/CORBA_macros.h"

TAO_BEGIN_VERSIONED_NAMESPACE_DECL

namespace CORBA
{
  class Environment;
}

namespace TAO_Notify
{

/// A forward declaration.
class Topology_Object;

/**
 * \brief An interface for an object that loads Persistent Topology Information.
 *
 * A persistent store must provide an implemention this interface.
 *
 */
class TAO_Notify_Serv_Export Topology_Loader
{
public:
  /// The constructor.
  Topology_Loader ();

  /// The destructor.
  virtual ~Topology_Loader ();

  /** \brief Begin the restore process.
   *
   * Call this function to start the reload of data from a persistent store.
   * When the Topology_Loader detects a child object, it should
   * call the load_child method of the object passed in, then do the same
   * loading process on the returned object.
   */
  virtual void load (Topology_Object *root) = 0;

  /**
   * \brief Close the loader after loading is complete.
   *
   * This is not pure virtual because some loaders may not need to be closed.
   * The default implementation does nothing.
   *
   * There should be a corresponding open, but the signature may
   * vary based on the type of loader, so we can't include it in the
   * interface.
   */
  virtual void close (void);
};

} // namespace TAO_Notify

TAO_END_VERSIONED_NAMESPACE_DECL

#include /**/ "ace/post.h"

#endif /* TOPOLOGY_LOADER */


text:
<?php

namespace Stash\Test\Stubs;

use Stash;
use Stash\Test\Exception\TestException;
use Stash\Interfaces\DriverInterface;

/**
 * DriverExceptionStub is used for testing how Stash reacts to thrown errors. Every function but the constructor throws
 * an exception.
 *
 * @package Stash
 * @author  Robert Hafner <tedivm@tedivm.com>
 *
 * @codeCoverageIgnore
 */
class DriverExceptionStub implements DriverInterface
{
    protected $store = array();

    public function setOptions(array $options = array())
    {
    }

    public function __destruct()
    {
    }

    public function getData($key)
    {
        throw new TestException('Test exception for ' . __FUNCTION__ . ' call');
    }

    protected function getKeyIndex($key)
    {
        throw new TestException('Test exception for ' . __FUNCTION__ . ' call');
    }

    public function storeData($key, $data, $expiration)
    {
        throw new TestException('Test exception for ' . __FUNCTION__ . ' call');
    }

    public function clear($key = null)
    {
        throw new TestException('Test exception for ' . __FUNCTION__ . ' call');
    }

    public function purge()
    {
        throw new TestException('Test exception for ' . __FUNCTION__ . ' call');
    }

    public function canEnable()
    {
        return (defined('TESTING') && TESTING);
    }

    public static function isAvailable()
    {
        return (defined('TESTING') && TESTING);
    }
}


text:
/*
 Crypti delegates API calls
 */

var private = {}, self = null,
library = null, modules = null;

/**
 * Creates instance of Delegates API. Use *modules.api.delegates* to get existing object.
 *
 * @param cb - Callback.
 * @param _library - Object that contains helpers.
 * @constructor
 */
function Delegates(cb, _library) {
	self = this;
	library = _library;
	cb(null, self);
}

/**
 * Get delegate by filter.
 * @param filter - Filter to get delegate.
 * @param filter.transactionId - Id of transaction where delegate registered.
 * @param filter.publicKey - Public key of delegate.
 * @param filter.username - Username of delegate.
 * @param {Delegates~getDelegateCallback} cb - Callback handles response from Crypti.
 */
Delegates.prototype.getDelegate = function (filter, cb) {
	var message = {
		call: "delegates#getDelegate",
		args: {
			transactionId: filter.transactionId,
			publicKey: filter.publicKey,
			username: filter.username
		}
	};

	library.sandbox.sendMessage(message, cb);
}

/**
 * @callback Delegates~getDelegateCallback
 * @param error - Error of api call execution.
 * @param response - Response of api call execution.
 * @param response.delegate - Delegate object.
 * @param response.delegate.username - Username of delegate.
 * @param response.delegate.vote - Amount of votes for delegate.
 * @param response.delegate.address - Address of delegate.
 * @param response.delegate.publicKey - Public key of delegate.
 * @param response.delegate.rate - Position of delegate in delegates list.
 * @param response.delegate.productivity - Productivity of delegate.
 */

/**
 * Get delegate by filter.
 *
 * @param filter - Filter to get delegates.
 * @param filter.limit - Limit of delegates to get.
 * @param filter.offset - Offset of delegates to get.
 * @param filter.orderBy - Order by field to sort delegates.
 * @param {Delegates~getDelegatesCallback} cb - Callback handles response from Crypti.
 */
Delegates.prototype.getDelegates = function (filter, cb) {
	var message = {
		call: "delegates#getDelegates",
		args: {
			limit: filter.limit,
			offset: filter.offset,
			orderBy: filter.orderBy
		}
	};

	library.sandbox.sendMessage(message, cb);
}

/**
 * @callback Delegates~getDelegatesCallback
 * @param error - Error of api call execution.
 * @param response - Response of api call execution.
 * @param response.delegates - Array of delegates.
 */

/**
 * Get fee amount of delegate registration.
 *
 * @param {Delegates~getFeeCallback} cb - Callback handles response from Crypti.
 */
Delegates.prototype.getFee = function (cb) {
	var message = {
		call: "delegates#getFee",
		args: {}
	};

	library.sandbox.sendMessage(message, cb);
}

/**
 * @callback Delegates~getFeeCallback
 *
 * @param error - Error of api call execution.
 * @param response - Response of api call execution.
 * @param response.fee - Amount of fee to register delegate.
 */

/**
 * Get amount forged by delegate.
 * @param generatorPublicKey - Public key of delegate.
 * @param {Delegates~getForgedByAccount} cb - Callback handles response from Crypti.
 */
Delegates.prototype.getForgedByAccount = function (generatorPublicKey, cb) {
	var message = {
		call: "delegates#getForgedByAccount",
		args: {
			generatorPublicKey: generatorPublicKey
		}
	};

	library.sandbox.sendMessage(message, cb);
}

/**
 * @callback Delegates~getForgedByAccount
 *
 * @param error - Error of api call execution.
 * @param response - Response of api call execution.
 * @param response.fees - Amount of XCR that delegate forged.
 */

/**
 * Register delegate.
 * @param secret - Secret key of account.
 * @param publicKey - Public key of account (optional).
 * @param secondSecret - Second secret of account, if second signature enabled (optional).
 * @param username - Username to register.
 * @param {Delegates~addDelegate} cb - Callback handles response from Crypti.
 */
Delegates.prototype.addDelegate = function (secret, publicKey, secondSecret, username, cb) {
	var message = {
		call: "delegates#addDelegate",
		args: {
			secret: secret,
			publicKey: publicKey,
			secondSecret: secondSecret,
			username: username
		}
	};

	library.sandbox.sendMessage(message, cb);
}

/**
 * @callback Delegates~addDelegate
 * @param error - Error of api call execution.
 * @param response - Response of api call execution.
 * @param response.transactionId - Id of sent transaction.
 */

Delegates.prototype.onBind = function (_modules) {
	modules = _modules;
}

module.exports = Delegates;


text:
package com.landawn.abacus.util;

/**
 *
 * @since 0.8
 *
 * @author Haiyang Li
 */
public final class IndexedByte extends AbstractIndexed {
    private final byte value;

    IndexedByte(long index, byte value) {
        super(index);
        this.value = value;
    }

    public static IndexedByte of(byte value, int index) {
        N.checkArgNotNegative(index, "index");

        return new IndexedByte(index, value);
    }

    public static IndexedByte of(byte value, long index) {
        N.checkArgNotNegative(index, "index");

        return new IndexedByte(index, value);
    }

    public static ObjIterator<IndexedByte> of(final ByteIterator iter) {
        return of(iter, 0);
    }

    public static ObjIterator<IndexedByte> of(final ByteIterator iter, final int startIndex) {
        return of(iter, (long) startIndex);
    }

    public static ObjIterator<IndexedByte> of(final ByteIterator iter, final long startIndex) {
        if (startIndex < 0) {
            throw new IllegalArgumentException("Invalid start index: " + startIndex);
        }

        return new ObjIterator<IndexedByte>() {
            private long idx = startIndex;

            @Override
            public boolean hasNext() {
                return iter.hasNext();
            }

            @Override
            public IndexedByte next() {
                return IndexedByte.of(iter.nextByte(), idx++);
            }
        };
    }

    public byte value() {
        return value;
    }

    @Override
    public int hashCode() {
        return (int) index + value * 31;
    }

    @Override
    public boolean equals(Object obj) {
        return obj instanceof IndexedByte && ((IndexedByte) obj).index == index && N.equals(((IndexedByte) obj).value, value);
    }

    @Override
    public String toString() {
        return "[" + index + "]=" + value;
    }
}


text:
namespace NumberWithStep3
{
    using System;

    public class Startup
    {
        public static void Main()
        {
            int nthNumber = int.Parse(Console.ReadLine());

            for (int nums = 1; nums <= nthNumber; nums += 3)
            {
                Console.WriteLine(nums);
            }
        }
    }
}


text:
#ifndef _ADAPTER__SERVER_H_
#define _ADAPTER__SERVER_H_

#include <Python.h>
#include <grpc/grpc.h>

typedef struct { PyObject_HEAD grpc_server *c_server; } Server;

int pygrpc_add_server(PyObject *module);

#endif /* _ADAPTER__SERVER_H_ */


text:
package io.subutai.common.network;

import java.util.Set;

import org.apache.commons.lang3.StringUtils;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.Sets;

public class P2pLogs
{
    Set<String> logs = Sets.newHashSet();

    public void addLog( String log )
    {
        Preconditions.checkArgument( !StringUtils.isBlank( log ) );

        logs.add( log );
    }

    public Set<String> getLogs()
    {
        return logs;
    }

    public boolean isEmpty()
    {
        return logs.isEmpty();
    }
}


text:
export async function hasNext<T>(t: any, source: AsyncIterator<T>, expected: T) {
  const { done, value } = await source.next();
  t.false(done);
  t.deepEqual(expected, value);
}

export async function noNext<T>(t: any, source: AsyncIterator<T>) {
  const next = await source.next();
  t.true(next.done);
}


text:
export module Model {
    'use strict';

    export class ErrorsModel<T> {
        public Type:string;
        public Errors:T[];

        constructor() {
            this.Errors = [];
        }

        public HasErrors():boolean {
            return this.Errors && this.Errors.length > 0;
        }
    }
}


text:
require 'swing'

class Swing::JMenuBar

  # Override post-processing (non-setter) options given to initialize
  def post_process opts
    super
    # Create menu structure from :structure opt
    structure = opts.delete :structure
    if structure
      [structure].flatten.each do |element|
        case element
          when Hash # Hash defines menu structure
            element.each do |menu_name, menu_structure|
              menu = Swing::JMenu.new menu_name.to_s, :parent => self
              menu_structure.each do |item_name, item_action|
                Swing::JMenuItem.new item_name.to_s, :parent => menu, &item_action
              end
            end
          else
            self.add element
        end
      end
    end
  end

  # Proper way to add menu bar to its parent
  def attach_to parent
    parent.setJMenuBar self if parent and parent.respond_to? :setJMenuBar
  end
end


text:
// This file was generated by NxParameterized/scripts/GenParameterized.pl
// Created: 2015.06.02 04:12:11

#include "EmitterGeomExplicitParams_0p0.h"
#include <string.h>
#include <stdlib.h>

using namespace NxParameterized;

namespace physx
{
namespace apex
{

using namespace EmitterGeomExplicitParams_0p0NS;

const char* const EmitterGeomExplicitParams_0p0Factory::vptr =
    NxParameterized::getVptr<EmitterGeomExplicitParams_0p0, EmitterGeomExplicitParams_0p0::ClassAlignment>();

const physx::PxU32 NumParamDefs = 5;
static NxParameterized::DefinitionImpl* ParamDefTable; // now allocated in buildTree [NumParamDefs];

static const size_t ParamLookupChildrenTable[] =
{
	1, 3, 2, 4,
};

#define TENUM(type) physx::##type
#define CHILDREN(index) &ParamLookupChildrenTable[index]
static const NxParameterized::ParamLookupNode ParamLookupTable[NumParamDefs] =
{
	{ TYPE_STRUCT, false, 0, CHILDREN(0), 2 },
	{ TYPE_ARRAY, true, (size_t)(&((ParametersStruct*)0)->positions), CHILDREN(2), 1 }, // positions
	{ TYPE_VEC3, false, 1 * sizeof(physx::PxVec3), NULL, 0 }, // positions[]
	{ TYPE_ARRAY, true, (size_t)(&((ParametersStruct*)0)->velocities), CHILDREN(3), 1 }, // velocities
	{ TYPE_VEC3, false, 1 * sizeof(physx::PxVec3), NULL, 0 }, // velocities[]
};

bool EmitterGeomExplicitParams_0p0::mBuiltFlag = false;
NxParameterized::MutexType EmitterGeomExplicitParams_0p0::mBuiltFlagMutex;

EmitterGeomExplicitParams_0p0::EmitterGeomExplicitParams_0p0(NxParameterized::Traits* traits, void* buf, PxI32* refCount) :
	NxParameters(traits, buf, refCount)
{
	//mParameterizedTraits->registerFactory(className(), &EmitterGeomExplicitParams_0p0FactoryInst);

	if (!buf) //Do not init data if it is inplace-deserialized
	{
		initDynamicArrays();
		initStrings();
		initReferences();
		initDefaults();
	}
}

EmitterGeomExplicitParams_0p0::~EmitterGeomExplicitParams_0p0()
{
	freeStrings();
	freeReferences();
	freeDynamicArrays();
}

void EmitterGeomExplicitParams_0p0::destroy()
{
	// We cache these fields here to avoid overwrite in destructor
	bool doDeallocateSelf = mDoDeallocateSelf;
	NxParameterized::Traits* traits = mParameterizedTraits;
	physx::PxI32* refCount = mRefCount;
	void* buf = mBuffer;

	this->~EmitterGeomExplicitParams_0p0();

	NxParameters::destroy(this, traits, doDeallocateSelf, refCount, buf);
}

const NxParameterized::DefinitionImpl* EmitterGeomExplicitParams_0p0::getParameterDefinitionTree(void)
{
	if (!mBuiltFlag) // Double-checked lock
	{
		NxParameterized::MutexType::ScopedLock lock(mBuiltFlagMutex);
		if (!mBuiltFlag)
		{
			buildTree();
		}
	}

	return(&ParamDefTable[0]);
}

const NxParameterized::DefinitionImpl* EmitterGeomExplicitParams_0p0::getParameterDefinitionTree(void) const
{
	EmitterGeomExplicitParams_0p0* tmpParam = const_cast<EmitterGeomExplicitParams_0p0*>(this);

	if (!mBuiltFlag) // Double-checked lock
	{
		NxParameterized::MutexType::ScopedLock lock(mBuiltFlagMutex);
		if (!mBuiltFlag)
		{
			tmpParam->buildTree();
		}
	}

	return(&ParamDefTable[0]);
}

NxParameterized::ErrorType EmitterGeomExplicitParams_0p0::getParameterHandle(const char* long_name, Handle& handle) const
{
	ErrorType Ret = NxParameters::getParameterHandle(long_name, handle);
	if (Ret != ERROR_NONE)
	{
		return(Ret);
	}

	size_t offset;
	void* ptr;

	getVarPtr(handle, ptr, offset);

	if (ptr == NULL)
	{
		return(ERROR_INDEX_OUT_OF_RANGE);
	}

	return(ERROR_NONE);
}

NxParameterized::ErrorType EmitterGeomExplicitParams_0p0::getParameterHandle(const char* long_name, Handle& handle)
{
	ErrorType Ret = NxParameters::getParameterHandle(long_name, handle);
	if (Ret != ERROR_NONE)
	{
		return(Ret);
	}

	size_t offset;
	void* ptr;

	getVarPtr(handle, ptr, offset);

	if (ptr == NULL)
	{
		return(ERROR_INDEX_OUT_OF_RANGE);
	}

	return(ERROR_NONE);
}

void EmitterGeomExplicitParams_0p0::getVarPtr(const Handle& handle, void*& ptr, size_t& offset) const
{
	ptr = getVarPtrHelper(&ParamLookupTable[0], const_cast<EmitterGeomExplicitParams_0p0::ParametersStruct*>(&parameters()), handle, offset);
}

/* Dynamic Handle Indices */

void EmitterGeomExplicitParams_0p0::freeParameterDefinitionTable(NxParameterized::Traits* traits)
{
	if (!traits)
	{
		return;
	}

	if (!mBuiltFlag) // Double-checked lock
	{
		return;
	}

	NxParameterized::MutexType::ScopedLock lock(mBuiltFlagMutex);

	if (!mBuiltFlag)
	{
		return;
	}

	for (physx::PxU32 i = 0; i < NumParamDefs; ++i)
	{
		ParamDefTable[i].~DefinitionImpl();
	}

	traits->free(ParamDefTable);

	mBuiltFlag = false;
}

#define PDEF_PTR(index) (&ParamDefTable[index])

void EmitterGeomExplicitParams_0p0::buildTree(void)
{

	physx::PxU32 allocSize = sizeof(NxParameterized::DefinitionImpl) * NumParamDefs;
	ParamDefTable = (NxParameterized::DefinitionImpl*)(mParameterizedTraits->alloc(allocSize));
	memset(static_cast<void*>(ParamDefTable), 0, allocSize);

	for (physx::PxU32 i = 0; i < NumParamDefs; ++i)
	{
		NX_PARAM_PLACEMENT_NEW(ParamDefTable + i, NxParameterized::DefinitionImpl)(*mParameterizedTraits);
	}

	// Initialize DefinitionImpl node: nodeIndex=0, longName=""
	{
		NxParameterized::DefinitionImpl* ParamDef = &ParamDefTable[0];
		ParamDef->init("", TYPE_STRUCT, "STRUCT", true);

	}

	// Initialize DefinitionImpl node: nodeIndex=1, longName="positions"
	{
		NxParameterized::DefinitionImpl* ParamDef = &ParamDefTable[1];
		ParamDef->init("positions", TYPE_ARRAY, NULL, true);

#ifdef NX_PARAMETERIZED_HIDE_DESCRIPTIONS

#else

		static HintImpl HintTable[1];
		static Hint* HintPtrTable[1] = { &HintTable[0], };
		HintTable[0].init("shortDescription", "Initial Positions List", true);
		ParamDefTable[1].setHints((const NxParameterized::Hint**)HintPtrTable, 1);

#endif /* NX_PARAMETERIZED_HIDE_DESCRIPTIONS */

		ParamDef->setArraySize(-1);
	}

	// Initialize DefinitionImpl node: nodeIndex=2, longName="positions[]"
	{
		NxParameterized::DefinitionImpl* ParamDef = &ParamDefTable[2];
		ParamDef->init("positions", TYPE_VEC3, NULL, true);

#ifdef NX_PARAMETERIZED_HIDE_DESCRIPTIONS

#else

		static HintImpl HintTable[1];
		static Hint* HintPtrTable[1] = { &HintTable[0], };
		HintTable[0].init("shortDescription", "Initial Positions List", true);
		ParamDefTable[2].setHints((const NxParameterized::Hint**)HintPtrTable, 1);

#endif /* NX_PARAMETERIZED_HIDE_DESCRIPTIONS */

	}

	// Initialize DefinitionImpl node: nodeIndex=3, longName="velocities"
	{
		NxParameterized::DefinitionImpl* ParamDef = &ParamDefTable[3];
		ParamDef->init("velocities", TYPE_ARRAY, NULL, true);

#ifdef NX_PARAMETERIZED_HIDE_DESCRIPTIONS

#else

		static HintImpl HintTable[1];
		static Hint* HintPtrTable[1] = { &HintTable[0], };
		HintTable[0].init("shortDescription", "Initial Velocities List", true);
		ParamDefTable[3].setHints((const NxParameterized::Hint**)HintPtrTable, 1);

#endif /* NX_PARAMETERIZED_HIDE_DESCRIPTIONS */

		ParamDef->setArraySize(-1);
	}

	// Initialize DefinitionImpl node: nodeIndex=4, longName="velocities[]"
	{
		NxParameterized::DefinitionImpl* ParamDef = &ParamDefTable[4];
		ParamDef->init("velocities", TYPE_VEC3, NULL, true);

#ifdef NX_PARAMETERIZED_HIDE_DESCRIPTIONS

#else

		static HintImpl HintTable[1];
		static Hint* HintPtrTable[1] = { &HintTable[0], };
		HintTable[0].init("shortDescription", "Initial Velocities List", true);
		ParamDefTable[4].setHints((const NxParameterized::Hint**)HintPtrTable, 1);

#endif /* NX_PARAMETERIZED_HIDE_DESCRIPTIONS */

	}

	// SetChildren for: nodeIndex=0, longName=""
	{
		static Definition* Children[2];
		Children[0] = PDEF_PTR(1);
		Children[1] = PDEF_PTR(3);

		ParamDefTable[0].setChildren(Children, 2);
	}

	// SetChildren for: nodeIndex=1, longName="positions"
	{
		static Definition* Children[1];
		Children[0] = PDEF_PTR(2);

		ParamDefTable[1].setChildren(Children, 1);
	}

	// SetChildren for: nodeIndex=3, longName="velocities"
	{
		static Definition* Children[1];
		Children[0] = PDEF_PTR(4);

		ParamDefTable[3].setChildren(Children, 1);
	}

	mBuiltFlag = true;

}
void EmitterGeomExplicitParams_0p0::initStrings(void)
{
}

void EmitterGeomExplicitParams_0p0::initDynamicArrays(void)
{
	positions.buf = NULL;
	positions.isAllocated = true;
	positions.elementSize = sizeof(physx::PxVec3);
	positions.arraySizes[0] = 0;
	velocities.buf = NULL;
	velocities.isAllocated = true;
	velocities.elementSize = sizeof(physx::PxVec3);
	velocities.arraySizes[0] = 0;
}

void EmitterGeomExplicitParams_0p0::initDefaults(void)
{

	freeStrings();
	freeReferences();
	freeDynamicArrays();

	initDynamicArrays();
	initStrings();
	initReferences();
}

void EmitterGeomExplicitParams_0p0::initReferences(void)
{
}

void EmitterGeomExplicitParams_0p0::freeDynamicArrays(void)
{
	if (positions.isAllocated && positions.buf)
	{
		mParameterizedTraits->free(positions.buf);
	}
	if (velocities.isAllocated && velocities.buf)
	{
		mParameterizedTraits->free(velocities.buf);
	}
}

void EmitterGeomExplicitParams_0p0::freeStrings(void)
{
}

void EmitterGeomExplicitParams_0p0::freeReferences(void)
{
}

} // namespace apex
} // namespace physx


text:
from time import time, sleep, asctime as _asctime
import sched
from random import randint
import logging
import logging.handlers
import sys,os
import readline
from readline import write_history_file, read_history_file
import zmq
from simplejson import dumps, load, loads
from dsat.message import send_vector, fast_parse_vector, extract_vector_from_dict
from dsat.state import _f
import dsat

print dsat.__version__

_to = sys.argv[1]
_mode = sys.argv[2]
_stable = sys.argv[3] == "bind"
_what = None if len(sys.argv) <= 4 else sys.argv[4]

my_logger = logging.getLogger('Logger')
my_logger.setLevel(logging.DEBUG)
handler = logging.handlers.SysLogHandler(address = '/dev/log')
my_logger.addHandler(handler)
def D(msg):
    my_logger.warning("%r:%s" % (os.getpid(), msg))

HIST = ".hist_zmq"
if not os.path.exists(HIST):
    write_history_file(HIST)
read_history_file(HIST)

### init phase load its parameters

context = zmq.Context()
client = context.socket(getattr( zmq, _mode))
sleep(1)
_boc =  _stable  and "bind" or "connect"
_cnx_mode = getattr(client, _boc )
_cnx_mode(_to)
if _mode == "SUB":
    client.setsockopt(zmq.SUBSCRIBE, '')
    print "USBSRCIRINB ALL"
sleep(1)

print "address: %r" % _to
print "PATTERN: %r" % _mode
print _boc

print "message template is: %s" % dumps(extract_vector_from_dict({}), indent=4)

abort = False
recv = False
message=_what
while message and not abort:
    if "q" == message:
        break
    if "r" == _what:
        recv=True
    elif _what:
        message = _what
        abort = True
    else:
        message = "".join(iter(lambda :raw_input("%s >" % _to), "ç"))
    try:
        if recv:
            cpt = 0
            while True:
                print "waiting ..."
                print  fast_parse_vector(client)
                print "RECEVIED"
                print (" " * cpt ) + [ "\\", "-" , "/" , "|" ][cpt%4]
                cpt += 1
        else:
            print("SENT %s" % loads(message))
            print "\n"
            print client.socket_type
            send_vector(client, loads(message))

    except Exception as e:
        print(repr(e))

    D("sent %r" % message)
write_history_file(HIST)


text:
package org.apache.jena.tdbloader4;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.io.IOException;

import org.apache.hadoop.util.ToolRunner;
import org.apache.jena.tdbloader4.Constants;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import cmd.tdbloader4;

import com.hp.hpl.jena.tdb.base.file.Location;
import com.hp.hpl.jena.tdb.store.DatasetGraphTDB;
import com.hp.hpl.jena.tdb.sys.SetupTDB;

public class TestTDBLoader4MiniMRCluster extends AbstractMiniMRClusterTest {

    @BeforeClass public static void before() throws IOException {
    	startCluster() ;
    }

    @AfterClass public static void after() throws IOException {
    	stopCluster() ;
    }

    @Test public void test() throws Exception {
        String input = "src/test/resources/input" ;
        String output = "target/output" ;
        String[] args = new String[] {
                "-conf", config,
                "-D", Constants.OPTION_OVERRIDE_OUTPUT + "=true",
                "-D", Constants.OPTION_COPY_TO_LOCAL + "=true",
                "-D", Constants.OPTION_VERIFY + "=true",
                "-D", Constants.OPTION_RUN_LOCAL + "=false",
                "-D", Constants.OPTION_NUM_REDUCERS + "=3",
                "-D", Constants.OPTION_NUM_SAMPLES + "=40",
                input,
                output
        };
        assertEquals ( 0, ToolRunner.run(new tdbloader4(), args) );
        DatasetGraphTDB dsgMem = tdbloader4.load(input);
        DatasetGraphTDB dsgDisk = SetupTDB.buildDataset(new Location(output)) ;
        assertTrue ( tdbloader4.dump(dsgMem, dsgDisk), tdbloader4.isomorphic ( dsgMem, dsgDisk ) );
    }

}


text:
package org.opensingular.requirement.connector.sei30.extensao.ws;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for Campo complex type.
 *
 *
The following schema fragment specifies the expected         content contained within this class.
 *
 *

 * <complexType name="Campo">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <all>
 *         <element name="Nome" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         <element name="Valor" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *       </all>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Campo", propOrder = {

})
public class Campo {

    @XmlElement(name = "Nome", required = true)
    protected String nome;
    @XmlElement(name = "Valor", required = true)
    protected String valor;

    /**
     * Gets the value of the nome property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getNome() {
        return nome;
    }

    /**
     * Sets the value of the nome property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setNome(String value) {
        this.nome = value;
    }

    /**
     * Gets the value of the valor property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getValor() {
        return valor;
    }

    /**
     * Sets the value of the valor property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setValor(String value) {
        this.valor = value;
    }

}


text:
import express from 'express';
import path from 'path';
import logger from 'morgan';
import cookieParser from 'cookie-parser';
import bodyParser from 'body-parser';
import compression from 'compression';
import helmet from 'helmet';
import session from 'express-session';
import connectRedis from 'connect-redis';
import 'colors';

import config from './config.json';
import router from './routes/index';

const app = express();
const isProduction = process.env.NODE_ENV === 'production';
const port = process.env.PORT || config.http_port;
const RedisStore = connectRedis(session);
const server = require('http').createServer(app);

if (isProduction) {
  app.use(helmet());
  app.disable('x-powered-by');
  app.use(logger('combined'));
  app.set('trust proxy', 1);
} else {
  app.use(logger('dev'));
}

app.use(compression());
app.use(bodyParser.json({
  limit: '20mb',
}));
app.use(bodyParser.urlencoded({
  limit: '20mb',
  extended: true,
}));
app.use(cookieParser());
app.use(session({
  store: new RedisStore({
    host: isProduction ? config.redis_hostname_prod : config.redis_hostname_dev,
    port: config.redis_port,
  }),
  secret: 'keyboard cat',
  saveUninitialized: false,
  resave: false,
  cookie: {
    httpOnly: !isProduction,
    secure: isProduction,
  },
}));

// api router
app.use('/api/v1', router);

if (isProduction) {
  // Serve dist files if is production mode
  const distPath = path.resolve(__dirname, '../frontend/dist/prod');
  app.use(express.static(distPath));
  app.get('*', (_, res) => {
    res.sendFile(`${distPath}/index.html`);
  });
} else {
  // Return 404 for non-exist api
  app.get('*', (req, res) => {
    res.status(404).send(`Api not exist for ${req.url}`);
  });
}

// Start server listen on specific port
server.listen(port, (error) => {
  if (error) {
    console.error(`\n${error}`);
    server.close();
    process.exit(1);
  }
  if (isProduction) {
    console.info(`\nExpress: Listening on port ${port}, open up http://localhost:${port}/ in your broswer!\n`.green);
  } else {
    console.info(`\nExpress: Serve api on http://localhost:${port}/ \n`);
  }
});

const stopHandler = (signal) => {
  console.error(`\nExit process in responding to %s`.red, signal);
  server.close();
  process.exit(1);
};

process.on('SIGTERM', stopHandler, 'SIGTERM');
process.on('SIGINT', stopHandler, 'SIGINT');
process.on('SIGHUP', stopHandler, 'SIGINT');


text:
package org.iotivity.base;

public class OcResourceHandle {

    private OcResourceHandle(long nativeHandle) {
        this.mNativeHandle = nativeHandle;
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();

        dispose();
    }

    private native void dispose();

    private long mNativeHandle;
}


text:
module Pure (module Export) where

-- from pure-core
import Pure.Data.View as Export hiding (On,content)
import Pure.Data.View.Patterns as Export

-- from pure-default
import Pure.Data.Default as Export

-- from pure-dom
import Pure.DOM as Export

-- from pure-lifted
import Pure.Data.Lifted as Export (JSV,Win(..),Doc(..),Head(..),Body(..),Element(..),Text(..),Node(..),Frag(..),IsNode(..),toJSV,Evt(..),Options(Options),prevDef,prevProp,onRaw,(.#),findByTag,findById,same,isNull,getWindow,getBody,getDocument,getHead,body,window,document,head)
import Pure.Animation as Export (addAnimation)
import Pure.IdleWork as Export (addIdleWork)

-- from pure-time
import Pure.Data.Time as Export

-- from pure-txt
import Pure.Data.Txt as Export (Txt,ToTxt(..),FromTxt(..))

-- from pure-events
import Pure.Data.Events as Export hiding (button,Accept,Alt,Select)

-- from pure-html
import Pure.Data.HTML as Export hiding (Head,Body,Style,Time)
import Pure.Data.HTML.Properties as Export hiding (Children,Data,Style,ContextMenu,Cite,Code,Form,Label,Span,Summary,Title,Bgcolor,Border,Color,Content,Height,Sizes,Width,Target)

-- from pure-theme; exports Pure.Data.Styles
import Pure.Theme as Export hiding (target,delay)

-- from pure-styles
import Pure.Data.Styles.Patterns as Export


text:
"""This module defines a mysqlctl based MySQL database.
"""

import os
import subprocess

import MySQLdb

from vttest import environment
from vttest import mysql_db
from vttest.mysql_flavor import mysql_flavor

class MySqlDBMysqlctl(mysql_db.MySqlDB):
  """Contains data and methods to manage a MySQL instance using mysqlctl."""

  def __init__(self, directory, port, extra_my_cnf, snapshot_file=None):
    super(MySqlDBMysqlctl, self).__init__(
        directory, port, extra_my_cnf, snapshot_file)

  def setup(self):
    cmd = [
        environment.mysqlctl_binary,
        '-alsologtostderr',
        '-tablet_uid', '1',
        '-mysql_port', str(self._port),
        'init',
        '-init_db_sql_file',
        os.path.join(os.environ['VTTOP'], 'config/init_db.sql'),
    ]
    env = os.environ
    env['VTDATAROOT'] = self._directory
    my_cnf = mysql_flavor().my_cnf()
    if self._extra_my_cnf:
      my_cnf += ':%s' % self._extra_my_cnf
    env['EXTRA_MY_CNF'] = my_cnf
    result = subprocess.call(cmd, env=env)
    if result != 0:
      raise Exception('mysqlctl failed', result)

  def teardown(self):
    cmd = [
        environment.mysqlctl_binary,
        '-alsologtostderr',
        '-tablet_uid', '1',
        '-mysql_port', str(self._port),
        'shutdown',
    ]
    result = subprocess.call(cmd)
    if result != 0:
      raise Exception('mysqlctl failed', result)

  def connect(self, db_name):
    return MySQLdb.connect(user='vt_dba',
                           unix_socket=self.unix_socket(),
                           db=db_name)

  def username(self):
    return 'vt_dba'

  def password(self):
    return ''

  def hostname(self):
    return ''

  def port(self):
    return self._port

  def unix_socket(self):
    return os.path.join(self._directory, 'vt_0000000001', 'mysql.sock')

  def config(self):
    return {
        'username': self.username(),
        'password': self.password(),
        'socket': self.unix_socket(),
    }


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Meldii.Updater
{
    class Program
    {
        static string MeldiiName = "Meldii.exe";

        static void Main(string[] args)
        {
            // Attempt to close all Meldii processes.
            // This will try every second for 5 seconds.
            int i = 0;
            while (i < 5)
            {
                var processes = Process.GetProcessesByName("meldii");
                processes = processes.Where(x => x.ProcessName != "Meldii.Updater.exe").ToArray();
                if (processes.Length == 0)
                    break;

                // Kill each process.
                foreach (var process in processes)
                    process.Kill();

                // Wait 1 second.
                Thread.Sleep(1000);
                ++i;
            }

            // Failed to close Meldii for whatever reason.
            if (i == 5)
            {
                Console.WriteLine("Error trying to close " + MeldiiName);
                return;
            }

            // Remove Meldii
            if (File.Exists(MeldiiName))
            {
                try
                {
                    File.Delete(MeldiiName);
                }
                catch (Exception)
                {
                    Console.WriteLine("Error trying to remove " + MeldiiName);
                    return;
                }
            }

            File.Move("Meldii_New.exe", MeldiiName);

            Process.Start(MeldiiName);
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using QuantConnect.Brokerages.Backtesting;
using QuantConnect.Interfaces;
using QuantConnect.Packets;

namespace QuantConnect.Brokerages.Paper
{
    /// <summary>
    /// The factory type for the <see cref="PaperBrokerage"/>
    /// </summary>
    public class PaperBrokerageFactory : IBrokerageFactory
    {
        /// <summary>
        /// Gets the type of brokerage produced by this factory
        /// </summary>
        public Type BrokerageType
        {
            get { return typeof(PaperBrokerage); }
        }

        /// <summary>
        /// Gets the brokerage data required to run the IB brokerage from configuration
        /// </summary>
        /// <remarks>
        /// The implementation of this property will create the brokerage data dictionary required for
        /// running live jobs. See <see cref="IJobQueueHandler.NextJob"/>
        /// </remarks>
        public Dictionary<string, string> BrokerageData
        {
            get { return new Dictionary<string, string>(); }
        }

        /// <summary>
        /// Gets a new instance of the <see cref="InteractiveBrokersBrokerageModel"/>
        /// </summary>
        public IBrokerageModel BrokerageModel
        {
            get { return new InteractiveBrokersBrokerageModel(); }
        }

        /// <summary>
        /// Gets a map of the default markets to be used for each security type
        /// </summary>
        public IReadOnlyDictionary<SecurityType, string> DefaultMarkets
        {
            get { return BacktestingBrokerageFactory.DefaultMarketMap; }
        }

        /// <summary>
        /// Creates a new IBrokerage instance
        /// </summary>
        /// <param name="job">The job packet to create the brokerage for</param>
        /// <param name="algorithm">The algorithm instance</param>
        /// <returns>A new brokerage instance</returns>
        public IBrokerage CreateBrokerage(LiveNodePacket job, IAlgorithm algorithm)
        {
            return new PaperBrokerage(algorithm, job);
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        /// <filterpriority>2</filterpriority>
        public void Dispose()
        {
            // NOP
        }
    }
}


text:
The PlasmaQuery™ API provides
a flexible mechanism to fully describe any arbitrary SDO results Data Graph, independent
of any persistence framework or type of data store.  PlasmaQuery™ supports XPath expressions as a free-text
"surface language", parsed by the API implementation and used to construct an
underlying query object model representation. As an alternative to free-text,
PlasmaQuery™ contains a query Domain Specific Language (DSL) generator and API
facilitating (IDE) code-completion, 100% compile-time checking and resulting in
code with an almost "fluent" English appearance based on your business model. At
runtime the PlasmaQuery™ DSL implementation constructs an underlying query
object model representation. The detailed query object model can also be
manipulated directly and consists of various criteria entities such as
expressions, properties, operators, parameters, etc… as well as convenient
factory operations which allow precise user and system control over the various
elements constituting a query. The object model can also be serialized as XML
for wire transport, persistence, flat file or other usage.        <o:p></o:p>


text:
<?php

namespace PhpSchool\PhpWorkshopTest;

use PHPUnit\Framework\TestCase;

use function PhpSchool\PhpWorkshop\any;
use function PhpSchool\PhpWorkshop\camel_case_to_kebab_case;
use function PhpSchool\PhpWorkshop\mb_str_pad;

class FunctionsTest extends TestCase
{
    /**
     * @dataProvider mbStrPadProvider
     */
    public function testMbStrPad(string $string, int $pad, string $expected): void
    {
        self::assertSame(mb_str_pad($string, $pad), $expected);
    }

    public function mbStrPadProvider(): array
    {
        return [
            ['hello', 10, 'hello     '],
            ['hello😂', 10, 'hello😂    '],
        ];
    }

    /**
     * @dataProvider camelCaseToKebabCaseProvider
     */
    public function testCamelCaseToKebabCase(string $string, string $expected): void
    {
        self::assertSame(camel_case_to_kebab_case($string), $expected);
    }

    public function camelCaseToKebabCaseProvider(): array
    {
        return [
            ['camelCase', 'camel-case'],
            [
                'educationIsThePassportToTheFutureForTomorrowBelongsToThoseWhoPrepareForItToday',
                'education-is-the-passport-to-the-future-for-tomorrow-belongs-to-those-who-prepare-for-it-today'
            ]
        ];
    }

    public function testAny(): void
    {
        self::assertEquals(true, any([1, 2, 3, 10, 11], function (int $num) {
            return $num > 10;
        }));

        self::assertEquals(false, any([1, 2, 3, 10, 11], function (int $num) {
            return $num > 11;
        }));
    }
}


text:
package com.appsfactory.app.android.eMenu.ui;

import android.app.FragmentManager;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;

import com.appsfactory.app.android.eMenu.R;
import com.appsfactory.app.android.eMenu.utils.Constants;
import com.nostra13.universalimageloader.core.ImageLoader;

public class HomeActivity extends BaseActivity implements
		DashboardFragment.Callbacks {
	DashboardFragment dbFragment;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_home);

		FragmentManager fm = getFragmentManager();
		dbFragment = (DashboardFragment) fm
				.findFragmentById(R.id.fragment_dashboard);
	}

	@Override
	public void onBackPressed() {
		dbFragment.popBackStack();
		if (dbFragment.isStackEmpty()) {
			ImageLoader.getInstance().destroy();
			Constants.setServerAddress("http://");
			super.onBackPressed();
		}

	}

	@Override
	protected void onResume() {
		super.onResume();
		// dbFragment.popBackStack();
	}

	// When fragment Item been clicked, add it to back stack
	@Override
	public void onItemClick() {

	}
}