text:
package doc

import (
	"archive/zip"
	"bytes"
	"errors"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"path"
	"regexp"
	"strings"

	"github.com/Unknwon/com"

	"github.com/Unknwon/gowalker/models"
	"github.com/Unknwon/gowalker/modules/base"
)

// TODO: specify with command line flag
const repoRoot = "/tmp/gw"

func init() {
	os.RemoveAll(repoRoot)
}

var urlTemplates = []struct {
	re       *regexp.Regexp
	template string
	lineFmt  string
}{
	{
		regexp.MustCompile(`^git\.gitorious\.org/(?P<repo>[^/]+/[^/]+)$`),
		"https://gitorious.org/{repo}/blobs/{tag}/{dir}{0}",
		"#line%d",
	},
	{
		regexp.MustCompile(`^camlistore\.org/r/p/(?P<repo>[^/]+)$`),
		"http://camlistore.org/code/?p={repo}.git;hb={tag};f={dir}{0}",
		"#l%d",
	},
}

// lookupURLTemplate finds an expand() template, match map and line number
// format for well known repositories.
func lookupURLTemplate(repo, dir, tag string) (string, map[string]string, string) {
	if strings.HasPrefix(dir, "/") {
		dir = dir[1:] + "/"
	}
	for _, t := range urlTemplates {
		if m := t.re.FindStringSubmatch(repo); m != nil {
			match := map[string]string{
				"dir": dir,
				"tag": tag,
			}
			for i, name := range t.re.SubexpNames() {
				if name != "" {
					match[name] = m[i]
				}
			}
			return t.template, match, t.lineFmt
		}
	}
	return "", nil, ""
}

type vcsCmd struct {
	schemes  []string
	download func([]string, string, string) (string, string, error)
}

var vcsCmds = map[string]*vcsCmd{
	"git": &vcsCmd{
		schemes:  []string{"http", "https", "git"},
		download: downloadGit,
	},
}

var lsremoteRe = regexp.MustCompile(`(?m)^([0-9a-f]{40})\s+refs/(?:tags|heads)/(.+)$`)

func downloadGit(schemes []string, repo, savedEtag string) (string, string, error) {
	var p []byte
	var scheme string
	for i := range schemes {
		cmd := exec.Command("git", "ls-remote", "--heads", "--tags", schemes[i]+"://"+repo+".git")
		log.Println(strings.Join(cmd.Args, " "))
		var err error
		p, err = cmd.Output()
		if err == nil {
			scheme = schemes[i]
			break
		}
	}

	if scheme == "" {
		return "", "", com.NotFoundError{"VCS not found"}
	}

	tags := make(map[string]string)
	for _, m := range lsremoteRe.FindAllSubmatch(p, -1) {
		tags[string(m[2])] = string(m[1])
	}

	tag, commit, err := bestTag(tags, "master")
	if err != nil {
		return "", "", err
	}

	etag := scheme + "-" + commit

	if etag == savedEtag {
		return "", "", ErrPackageNotModified
	}

	dir := path.Join(repoRoot, repo+".git")
	p, err = ioutil.ReadFile(path.Join(dir, ".git/HEAD"))
	switch {
	case err != nil:
		if err := os.MkdirAll(dir, 0777); err != nil {
			return "", "", err
		}
		cmd := exec.Command("git", "clone", scheme+"://"+repo, dir)
		log.Println(strings.Join(cmd.Args, " "))
		if err := cmd.Run(); err != nil {
			return "", "", err
		}
	case string(bytes.TrimRight(p, "\n")) == commit:
		return tag, etag, nil
	default:
		cmd := exec.Command("git", "fetch")
		log.Println(strings.Join(cmd.Args, " "))
		cmd.Dir = dir
		if err := cmd.Run(); err != nil {
			return "", "", err
		}
	}

	cmd := exec.Command("git", "checkout", "--detach", "--force", commit)
	cmd.Dir = dir
	if err := cmd.Run(); err != nil {
		return "", "", err
	}

	return tag, etag, nil
}

var (
	vcsPattern       = regexp.MustCompile(`^(?P<repo>(?:[a-z0-9.\-]+\.)+[a-z0-9.\-]+(?::[0-9]+)?/[A-Za-z0-9_.\-/]*?)\.(?P<vcs>bzr|git|hg|svn)(?P<dir>/[A-Za-z0-9_.\-/]*)?$`)
	gopkgPathPattern = regexp.MustCompile(`^/(?:([a-zA-Z0-9][-a-zA-Z0-9]+)/)?([a-zA-Z][-.a-zA-Z0-9]*)\.((?:v0|v[1-9][0-9]*)(?:\.0|\.[1-9][0-9]*){0,2})(?:\.git)?((?:/[a-zA-Z0-9][-.a-zA-Z0-9]*)*)$`)
)

func getVCSDoc(match map[string]string, etagSaved string) (*Package, error) {
	if strings.HasPrefix(match["importPath"], "golang.org/x/") {
		match["owner"] = "golang"
		match["repo"] = path.Dir(strings.TrimPrefix(match["importPath"], "golang.org/x/"))
		return getGithubDoc(match, etagSaved)
	} else if strings.HasPrefix(match["importPath"], "gopkg.in/") {
		m := gopkgPathPattern.FindStringSubmatch(strings.TrimPrefix(match["importPath"], "gopkg.in"))
		if m == nil {
			return nil, fmt.Errorf("unsupported gopkg.in import path: %s", match["importPath"])
		}
		user := m[1]
		repo := m[2]
		if len(user) == 0 {
			user = "go-" + repo
		}
		match["owner"] = user
		match["repo"] = repo
		match["tag"] = m[3]
		return getGithubDoc(match, etagSaved)
	}

	cmd := vcsCmds[match["vcs"]]
	if cmd == nil {
		return nil, com.NotFoundError{com.Expand("VCS not supported: {vcs}", match)}
	}

	scheme := match["scheme"]
	if scheme == "" {
		i := strings.Index(etagSaved, "-")
		if i > 0 {
			scheme = etagSaved[:i]
		}
	}

	schemes := cmd.schemes
	if scheme != "" {
		for i := range cmd.schemes {
			if cmd.schemes[i] == scheme {
				schemes = cmd.schemes[i : i+1]
				break
			}
		}
	}

	// Download and checkout.

	tag, _, err := cmd.download(schemes, match["repo"], etagSaved)
	if err != nil {
		return nil, err
	}

	// Find source location.

	urlTemplate, urlMatch, lineFmt := lookupURLTemplate(match["repo"], match["dir"], tag)

	// Slurp source files.

	d := path.Join(repoRoot, com.Expand("{repo}.{vcs}", match), match["dir"])
	f, err := os.Open(d)
	if err != nil {
		if os.IsNotExist(err) {
			err = com.NotFoundError{err.Error()}
		}
		return nil, err
	}
	fis, err := f.Readdir(-1)
	if err != nil {
		return nil, err
	}

	// Get source file data.
	var files []com.RawFile
	for _, fi := range fis {
		if fi.IsDir() || !base.IsDocFile(fi.Name()) {
			continue
		}
		b, err := ioutil.ReadFile(path.Join(d, fi.Name()))
		if err != nil {
			return nil, err
		}
		files = append(files, &Source{
			SrcName:   fi.Name(),
			BrowseUrl: com.Expand(urlTemplate, urlMatch, fi.Name()),
			SrcData:   b,
		})
	}

	// Start generating data.
	w := &Walker{
		LineFmt: lineFmt,
		Pdoc: &Package{
			PkgInfo: &models.PkgInfo{
				ImportPath: match["importPath"],
			},
		},
	}

	srcs := make([]*Source, 0, len(files))
	for _, f := range files {
		s, _ := f.(*Source)
		srcs = append(srcs, s)
	}

	return w.Build(&WalkRes{
		WalkDepth: WD_All,
		WalkType:  WT_Memory,
		WalkMode:  WM_All,
		Srcs:      srcs,
	})
}

var defaultTags = map[string]string{"git": "master", "hg": "default", "svn": "trunk"}

func bestTag(tags map[string]string, defaultTag string) (string, string, error) {
	if commit, ok := tags["go1"]; ok {
		return "go1", commit, nil
	}
	if commit, ok := tags[defaultTag]; ok {
		return defaultTag, commit, nil
	}
	return "", "", com.NotFoundError{"Tag or branch not found."}
}

// checkDir checks if directory has been appended to slice.
func checkDir(dir string, dirs []string) bool {
	for _, d := range dirs {
		if dir == d {
			return true
		}
	}
	return false
}

// Only support .zip.
func getRepoByArchive(match map[string]string, downloadPath string) (bool, string, []com.RawFile, []string, error) {
	stdout, _, err := com.ExecCmd("curl", downloadPath)
	if err != nil {
		return false, "", nil, nil, err
	}
	p := []byte(stdout)

	r, err := zip.NewReader(bytes.NewReader(p), int64(len(p)))
	if err != nil {
		return false, "", nil, nil, errors.New(downloadPath + " -> new zip: " + err.Error())
	}

	if len(r.File) == 0 {
		return false, "", nil, nil, nil
	}

	nameLen := strings.Index(r.File[0].Name, "/")
	dirPrefix := match["dir"]
	if len(dirPrefix) != 0 {
		dirPrefix = dirPrefix[1:] + "/"
	}
	preLen := len(dirPrefix)
	isGoPro := false

	// for k, v := range match {
	// 	println(k, v)
	// }
	comment := r.Comment

	files := make([]com.RawFile, 0, 5)
	dirs := make([]string, 0, 5)
	for _, f := range r.File {
		fileName := f.Name[nameLen+1:]
		// Skip directories and files in wrong directories, get them later.
		if strings.HasSuffix(fileName, "/") || !strings.HasPrefix(fileName, dirPrefix) {
			continue
		}
		//fmt.Println(fileName)

		// Get files and check if directories have acceptable files.
		if d, fn := path.Split(fileName); base.IsDocFile(fn) &&
			base.FilterDirName(d) {
			// Check if it's a Go file.
			if !isGoPro && strings.HasSuffix(fn, ".go") {
				isGoPro = true
			}

			// Check if file is in the directory that is corresponding to import path.
			if d == dirPrefix {
				// Yes.
				if !isGoPro && strings.HasSuffix(fn, ".go") {
					isGoPro = true
				}
				// Get file from archive.
				rc, err := f.Open()
				if err != nil {
					return isGoPro, comment, files, dirs,
						errors.New(downloadPath + " -> open file: " + err.Error())
				}

				p := make([]byte, f.FileInfo().Size())
				rc.Read(p)
				if err != nil {
					return isGoPro, comment, files, dirs,
						errors.New(downloadPath + " -> read file: " + err.Error())
				}
				//fmt.Println(com.Expand(match["browserUrlTpl"], match, fn))
				files = append(files, &Source{
					SrcName:   fn,
					BrowseUrl: com.Expand(match["browserUrlTpl"], match, fn),
					RawSrcUrl: com.Expand(match["rawSrcUrlTpl"], match, fileName[preLen:]),
					SrcData:   p,
				})

			} else {
				sd, _ := path.Split(d[preLen:])
				sd = strings.TrimSuffix(sd, "/")
				if !checkDir(sd, dirs) {
					dirs = append(dirs, sd)
				}
			}
		}
	}
	return isGoPro, comment, files, dirs, nil
}


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

import java.util.Set;
import javax.ws.rs.core.Application;

/**
 *
 * @author mfaour
 */
@javax.ws.rs.ApplicationPath("webresources")
public class ApplicationConfig extends Application {

    @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> resources = new java.util.HashSet<>();
        addRestResourceClasses(resources);
        return resources;
    }

    /**
     * Do not modify addRestResourceClasses() method.
     * It is automatically populated with
     * all resources defined in the project.
     * If required, comment out calling this method in getClasses().
     */
    private void addRestResourceClasses(Set<Class<?>> resources) {
        resources.add(StockManagement.Services.Resources.ActionResource.class);
        resources.add(StockManagement.Services.Resources.BranchResource.class);
        resources.add(StockManagement.Services.Resources.BrandResource.class);
        resources.add(StockManagement.Services.Resources.ChartResource.class);
        resources.add(StockManagement.Services.Resources.ClientResource.class);
        resources.add(StockManagement.Services.Resources.CompanyResource.class);
        resources.add(StockManagement.Services.Resources.MenuResource.class);
        resources.add(StockManagement.Services.Resources.OrderResource.class);
        resources.add(StockManagement.Services.Resources.ProductResource.class);
        resources.add(StockManagement.Services.Resources.RoleResource.class);
         resources.add(StockManagement.Services.Resources.SupplierResource.class);
         resources.add(StockManagement.Services.Resources.UserResource.class);
    }

}

redpajama_set_name: RedPajamaGithub


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

		<title>Model Validations Demo</title>

Observe Validations Demo

This demo demonstrates using validations to prevent
		a person's birthday from being in the future.

<input id='updater'/>


text:
"""Support for (EMEA/EU-based) Honeywell evohome systems."""
# Glossary:
#   TCS - temperature control system (a.k.a. Controller, Parent), which can
#   have up to 13 Children:
#     0-12 Heating zones (a.k.a. Zone), and
#     0-1 DHW controller, (a.k.a. Boiler)
# The TCS & Zones are implemented as Climate devices, Boiler as a WaterHeater
from datetime import timedelta
import logging

import requests.exceptions
import voluptuous as vol

from homeassistant.const import (
    CONF_SCAN_INTERVAL, CONF_USERNAME, CONF_PASSWORD,
    EVENT_HOMEASSISTANT_START)
from homeassistant.core import callback
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.discovery import load_platform
from homeassistant.helpers.dispatcher import async_dispatcher_send

_LOGGER = logging.getLogger(__name__)

DOMAIN = 'evohome'
DATA_EVOHOME = 'data_' + DOMAIN
DISPATCHER_EVOHOME = 'dispatcher_' + DOMAIN

CONF_LOCATION_IDX = 'location_idx'
SCAN_INTERVAL_DEFAULT = timedelta(seconds=300)
SCAN_INTERVAL_MINIMUM = timedelta(seconds=180)

CONFIG_SCHEMA = vol.Schema({
    DOMAIN: vol.Schema({
        vol.Required(CONF_USERNAME): cv.string,
        vol.Required(CONF_PASSWORD): cv.string,
        vol.Optional(CONF_LOCATION_IDX, default=0): cv.positive_int,
        vol.Optional(CONF_SCAN_INTERVAL, default=SCAN_INTERVAL_DEFAULT):
            vol.All(cv.time_period, vol.Range(min=SCAN_INTERVAL_MINIMUM)),
    }),
}, extra=vol.ALLOW_EXTRA)

CONF_SECRETS = [
    CONF_USERNAME, CONF_PASSWORD,
]

# These are used to help prevent E501 (line too long) violations.
GWS = 'gateways'
TCS = 'temperatureControlSystems'

# bit masks for dispatcher packets
EVO_PARENT = 0x01
EVO_CHILD = 0x02

def setup(hass, hass_config):
    """Create a (EMEA/EU-based) Honeywell evohome system.

    Currently, only the Controller and the Zones are implemented here.
    """
    evo_data = hass.data[DATA_EVOHOME] = {}
    evo_data['timers'] = {}

    # use a copy, since scan_interval is rounded up to nearest 60s
    evo_data['params'] = dict(hass_config[DOMAIN])
    scan_interval = evo_data['params'][CONF_SCAN_INTERVAL]
    scan_interval = timedelta(
        minutes=(scan_interval.total_seconds() + 59) // 60)

    import evohomeclient2

    try:
        client = evo_data['client'] = evohomeclient2.EvohomeClient(
            evo_data['params'][CONF_USERNAME],
            evo_data['params'][CONF_PASSWORD],
            debug=False
        )

    except evohomeclient2.AuthenticationError as err:
        _LOGGER.error(
            "setup(): Failed to authenticate with the vendor's server. "
            "Check your username and password are correct. "
            "Resolve any errors and restart HA. Message is: %s",
            err
        )
        return False

    except requests.exceptions.ConnectionError:
        _LOGGER.error(
            "setup(): Unable to connect with the vendor's server. "
            "Check your network and the vendor's status page. "
            "Resolve any errors and restart HA."
        )
        return False

    finally:  # Redact any config data that's no longer needed
        for parameter in CONF_SECRETS:
            evo_data['params'][parameter] = 'REDACTED' \
                if evo_data['params'][parameter] else None

    evo_data['status'] = {}

    # Redact any installation data that's no longer needed
    for loc in client.installation_info:
        loc['locationInfo']['locationId'] = 'REDACTED'
        loc['locationInfo']['locationOwner'] = 'REDACTED'
        loc['locationInfo']['streetAddress'] = 'REDACTED'
        loc['locationInfo']['city'] = 'REDACTED'
        loc[GWS][0]['gatewayInfo'] = 'REDACTED'

    # Pull down the installation configuration
    loc_idx = evo_data['params'][CONF_LOCATION_IDX]
    try:
        evo_data['config'] = client.installation_info[loc_idx]

    except IndexError:
        _LOGGER.error(
            "setup(): config error, '%s' = %s, but its valid range is 0-%s. "
            "Unable to continue. Fix any configuration errors and restart HA.",
            CONF_LOCATION_IDX, loc_idx, len(client.installation_info) - 1
        )
        return False

    if _LOGGER.isEnabledFor(logging.DEBUG):
        tmp_loc = dict(evo_data['config'])
        tmp_loc['locationInfo']['postcode'] = 'REDACTED'

        if 'dhw' in tmp_loc[GWS][0][TCS][0]:  # if this location has DHW...
            tmp_loc[GWS][0][TCS][0]['dhw'] = '...'

        _LOGGER.debug("setup(): evo_data['config']=%s", tmp_loc)

    load_platform(hass, 'climate', DOMAIN, {}, hass_config)

    if 'dhw' in evo_data['config'][GWS][0][TCS][0]:
        _LOGGER.warning(
            "setup(): DHW found, but this component doesn't support DHW."
        )

    @callback
    def _first_update(event):
        """When HA has started, the hub knows to retrieve it's first update."""
        pkt = {'sender': 'setup()', 'signal': 'refresh', 'to': EVO_PARENT}
        async_dispatcher_send(hass, DISPATCHER_EVOHOME, pkt)

    hass.bus.listen(EVENT_HOMEASSISTANT_START, _first_update)

    return True


text:
var equation = [];
var str = "";
var operator = "+-/*";
var isJustEqual = false;

function operate(op){
  if(isJustEqual){
    isJustEqual = false;
  }
  if(str.length == 0){
    //符号不能出现在开头
    return;
  }
  if(operator.indexOf(str.charAt(str.length-1))!=-1)//覆盖之前的运算符 //not str.length()!
    equation.pop();
  equation.push(op);
  str = equation.join("");
  document.getElementById("cal_display").innerHTML = str;
}

function digit(d){//在html中给onclick传参数
  if(isJustEqual){
    equation = [];
    isJustEqual = false;
  }
  if(d == '0')
    if(str.charAt(str.length-1) == '/')
      return;
  equation.push(d);
  str = equation.join("");
  document.getElementById("cal_display").innerHTML = str;
}

function dot(){
  if(isJustEqual){
    equation = [];
    equation.push("0.");
    isJustEqual = false;
    str = equation.join("");
  document.getElementById("cal_display").innerHTML = str;
    return;
  }
  if(str.length == 0 || operator.indexOf(str.charAt(str.length-1))!=-1 || str.charAt(str.length-1) == '.')
    return;
  equation.push('.');
  str = equation.join("");
  document.getElementById("cal_display").innerHTML = str;
}

function allClear(){
  isJustEqual = false;
  equation = [];
  str = equation.join("");
  document.getElementById("cal_display").innerHTML = str;
}

function equalTo(){
  if(str.charAt(str.length-1) == '.' || operator.indexOf(str.charAt(str.length-1))!=-1)
    return;//末尾是小数点或运算符时 等号无效
  console.log("1%%%%%%% "+equation);
  cal();
  console.log("2&&&&&&& "+str);
  document.getElementById("cal_display").innerHTML = str;
  equation = [];
  for(var index=0; index<str.length; index++)
    equation.push(str.charAt(index));
  isJustEqual = true;//置flag,表示刚刚进行了运算
  console.log(equation);
}

function cal(string){//纯粹连着算下去,结果取两位小数点
  var result = 0;
  var begin = 0;
  var end = 1;
  while(operator.indexOf(str.charAt(end)) == -1)
    end++;
  result += Number(str.substring(begin,end));
  begin = end+1;
  while(begin<str.length){
    var op = str.charAt(end);
    end+=2;
    while(operator.indexOf(str.charAt(end)) == -1)
      end++;
    var num = Number(str.substring(begin,end));
    if(op == '+')
      result+=num;
    else if(op == '-')
      result-=num;
    else if(op == '/')
      result/=(num*1.0);
    else if(op == '*')
      result*=(num*1.0);
    begin = end+1;
  }
  str = result.toString();
  console.log(" str === "+str);
}


text:
class Album < ActiveRecord::Base
  # attr_accessible :title, :body
  belongs_to :cover, :class_name => 'Resource'
  belongs_to :user
  has_many :resources, :as => :resourcable, :dependent => :destroy

  scope :active, :conditions => {:approved => true}

  def toggle_approved
    self.approved = self.approved ? false : true
    self.save
  end
end


text:
<form class="form-horizontal tab-form " novalidate ng-attr-name="{{view.editable && 'viewForm' || ''}}">

.{{view.id}}

    Script name

{{view.extension}}

        <input
          required
          pattern="[a-z0-9_-]*"
          name="extension"  class="form-control" type="text"
          ng-model="view.extension" placeholder="myview"/>

          You will use this as file extension while calling the API. Eg: http://../api.scriptName

          Error:
          Please specify the extension (dot excluded).
          Please only include letters, digits, underscores ('_') or hypens ('-').

    Script Content-Type

{{view['content-type']}}

        <select required
        class="form-control" ng-model="view['content\-type']" name="content-type">
          <option value="template/mustache">template/mustache</option>
          <option value="application/javascript">application/javascript</option>
        </select>

          Please indicate the language of the script:

JavaScript: application/javascript

Mustache: template/mustache

	          Error:
	          Please specify the type of script.
	          Please specify a valid Mime-Type, eg: application/ld+json.

.

    Returns Content-Type

{{view.type}}

        <input
         required
         pattern="^[a-z0-9\-]+\/[a-z0-9\+\-]+$"
         class="form-control" name="type" type="text" ng-model="view.type" placeholder="text/html"/>

          Error:
          Please specify the Content-Type to be returned (eg: text/html).
          Please specify a valid Mime-Type, eg: application/ld+json.

    Template

{{view.template}}

        <textarea
          required
          class="form-control" name="template" rows="10" ng-model="view.template"></textarea>

          Error:
          Write the script in the area above.

    <button ng-disabled="viewForm.$invalid" type="button" ng-click="save(view)" ng-switch-when="true" type="button" class="btn btn-success">Save</button>
    <button ng-show="view.id" type="button" ng-click="del(view)" ng-switch-when="true" type="button" class="btn btn-danger">Delete</button>
    Cancel
    Edit

</form>


text:
layout: base
title:  'Statistics of NUM in UD_Moksha-JR'
udver: '2'
---

## Treebank Statistics: UD_Moksha-JR: POS Tags: `NUM`

There are 12 `NUM` lemmas (1%), 15 `NUM` types (1%) and 37 `NUM` tokens (1%).
Out of 16 observed tags, the rank of `NUM` is: 10 in number of lemmas, 10 in number of types and 11 in number of tokens.

The 10 most frequent `NUM` lemmas: кафта, фкя, колма, вете, кемонь, 225, 7, кафонц, кеветие, комсь

The 10 most frequent `NUM` types:  фкя, кафта, колма, кафцьке, вете, 225, 7, Кемоньшка, кафонц, кеветиешка

The 10 most frequent ambiguous lemmas: вете (<tt>NUM</tt> 2, <tt>ADJ</tt> 1)

The 10 most frequent ambiguous types:

## Morphology

The form / lemma ratio of `NUM` is 1.250000 (the average of all parts of speech is 1.498347).

The 1st highest number of forms (2) was observed with the lemma "кафта": кафта, кафцьке.

The 2nd highest number of forms (2) was observed with the lemma "кемонь": Кемоньшка, кемотть.

The 3rd highest number of forms (2) was observed with the lemma "колма": колма, колмоцьке.

`NUM` occurs with 5 features: <tt>NumType</tt> (34; 92% instances), <tt>Case</tt> (33; 89% instances), <tt>Number</tt> (33; 89% instances), <tt>Definite</tt> (28; 76% instances), <tt>NumForm</tt> (2; 5% instances)

`NUM` occurs with 10 feature-value pairs: `Case=Cmp`, `Case=Nom`, `Definite=Ind`, `NumForm=Digit`, `NumType=Card`, `NumType=Coll`, `NumType=Sets`, `Number=Plur`, `Number=Plur,Sing`, `Number=Sing`

`NUM` occurs with 9 feature combinations.
The most frequent feature combination is `Case=Nom|Definite=Ind|Number=Sing|NumType=Card` (23 tokens).
Examples: кафта, фкя, колма, вете, комсь, ниле

## Relations

`NUM` nodes are attached to their parents using 4 different relations: <tt>nummod</tt> (34; 92% instances), <tt>conj</tt> (1; 3% instances), <tt>nmod</tt> (1; 3% instances), <tt>nsubj</tt> (1; 3% instances)

Parents of `NUM` nodes belong to 2 different parts of speech: <tt>NOUN</tt> (36; 97% instances), <tt>VERB</tt> (1; 3% instances)

36 (97%) `NUM` nodes are leaves.

0 (0%) `NUM` nodes have one child.

1 (3%) `NUM` nodes have two children.

The highest child degree of a `NUM` node is 2.

Children of `NUM` nodes are attached using 2 different relations: <tt>advmod</tt> (1; 50% instances), <tt>cc</tt> (1; 50% instances)

Children of `NUM` nodes belong to 2 different parts of speech: <tt>ADV</tt> (1; 50% instances), <tt>CCONJ</tt> (1; 50% instances)


text:
#include "src/actions/ctl/request_body_access.h"

#include <iostream>
#include <string>

#include "modsecurity/rules_set_properties.h"
#include "modsecurity/transaction.h"

namespace modsecurity {
namespace actions {
namespace ctl {

bool RequestBodyAccess::init(std::string *error) {
    std::string what(m_parser_payload, 18, m_parser_payload.size() - 18);

    if (what == "true") {
        m_request_body_access = true;
    } else if (what == "false") {
        m_request_body_access = false;
    } else {
        error->assign("Internal error. Expected: true or false, got: " \
            + m_parser_payload);
        return false;
    }

    return true;
}

bool RequestBodyAccess::evaluate(RuleWithActions *rule, Transaction *transaction) {
    if (m_request_body_access) {
        transaction->m_requestBodyAccess = RulesSetProperties::TrueConfigBoolean;
    } else {
        transaction->m_requestBodyAccess = RulesSetProperties::FalseConfigBoolean;
    }

    return true;
}

}  // namespace ctl
}  // namespace actions
}  // namespace modsecurity


text:
<!doctype html>
<meta charset=utf-8>
<title>Properties of the window object</title>
<link rel="author" title="Ms2ger" href="mailto:Ms2ger@gmail.com">
<link rel="help" href="http://ecma-international.org/ecma-262/5.1/#sec-15.1">
<link rel="help" href="https://webidl.spec.whatwg.org/#interface-prototype-object">
<link rel="help" href="https://webidl.spec.whatwg.org/#es-attributes">
<link rel="help" href="https://webidl.spec.whatwg.org/#es-operations">
<link rel="help" href="https://dom.spec.whatwg.org/#eventtarget">
<link rel="help" href="https://html.spec.whatwg.org/multipage/#window">
<link rel="help" href="https://html.spec.whatwg.org/multipage/#windowtimers">
<link rel="help" href="https://html.spec.whatwg.org/multipage/#windowbase64">
<link rel="help" href="https://html.spec.whatwg.org/multipage/#windowsessionstorage">
<link rel="help" href="https://html.spec.whatwg.org/multipage/#windowlocalstorage">
<link rel="help" href="https://dvcs.w3.org/hg/editing/raw-file/tip/editing.html#dom-window-getselection">
<link rel="help" href="http://dev.w3.org/csswg/cssom/#widl-def-Window">
<link rel="help" href="http://dev.w3.org/csswg/cssom-view/#widl-def-Window">


text:
import { TagState } from "./CombatantState";

export interface PlayerViewCombatantState {
  Name: string;
  HPDisplay: string;
  HPColor: string;
  Initiative: number;
  Id: string;
  Tags: TagState[];
  IsPlayerCharacter: boolean;
  ImageURL: string;
  AC?: number;
  Color?: string;
}


text:
package io.leftshift.sample.parser;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Weather {

    @SerializedName("id")
    @Expose
    public int id;
    @SerializedName("main")
    @Expose
    public String main;
    @SerializedName("description")
    @Expose
    public String description;
    @SerializedName("icon")
    @Expose
    public String icon;

}


text:
import React from 'react';
import CreateCollectionFormField from '../components/CreateCollectionFormField';

export default class CreateCollectionForm extends React.Component {
	constructor(props) {
    super(props);
    this.state = {
      title: '',
      collection_props: [{ 'property': 'text' }],
      user_id: 1
    }
    this.addProperty = this.addProperty.bind(this);
    this.handleTitleChange = this.handleTitleChange.bind(this);
    this.handleInputChange = this.handleInputChange.bind(this);
  }

	addProperty(e) {
		e.preventDefault();
		let newProps = this.state.collection_props.slice();
		newProps.push({'property': 'text'});

		this.setState({collection_props: newProps})
	}

	handleTitleChange(e) {
		let newTitle = e.target.value;
		this.setState({title: newTitle})
	}

	handleInputChange(e, index) {
		let field = e.target.parentNode;
		let prop = {};
		prop[field.firstChild.value] = field.lastChild.value;

		let props = this.state.collection_props.slice();
		props[index] = prop;
		this.setState({collection_props: props})
	}

	render() {
		let propsFields = this.state.collection_props.map((props, index) => {
			return <CreateCollectionFormField key={index} fieldIndex={index} updateProps={this.handleInputChange} />
		})

    return (
    	<form onSubmit={(e) => this.props.addCollection(e, this.state.title, this.state.collection_props, this.state.user_id)}>

Create New Collection

    		<input type="text" placeholder="Collection Title" onChange={this.handleTitleChange} />
    		{ propsFields }
    		<button className="btn btn-default" onClick={this.addProperty}>Add property</button>
    		<button className="btn btn-default" type="submit">Create Collection</button>
    	</form>
    )
	}
}


text:
LUCIDAROOT=$(pwd)/../../
git clone https://github.com/bpotard/idlak.git
mv idlak kaldi_tts
cd kaldi_tts
git checkout 02b24dc6f79b84779e423bfbb17bdf8e70c95aec
cd tools
extras/check_dependencies.sh
cp ../../install_idlak.sh . # contains modifications
make
cd ..
cd src
sed -i '7s/^/COMPILE_FLAGS += -fPIC\n/' Makefile
./configure --shared
make depend
make
cd ..
cd egs/tts_dnn_arctic/s1
./run.sh
# Replace the following text with your own.
echo '########## Test: This is a test from Lucida.'
echo 'This is a test from Lucida.' | utils/synthesis_test.sh
echo 'Please "cd exp_dnn/tts_dnn_train_3_deltasc2_quin5/tst_forward_tmp/wav_mlpg" to retrieve the audio!'


text:
/**
 * Package containing the servlet code.  It is responsible for the API.
 */
package org.mapfish.print.servlet;


text:
#ifndef CGPATH_H_
#define CGPATH_H_

typedef struct CGPath *CGMutablePathRef;
typedef const struct CGPath *CGPathRef;

#include <CoreGraphics/CGBase.h>
#include <CoreGraphics/CGAffineTransform.h>
#include <CoreFoundation/CFBase.h>

CG_EXTERN_C_BEGIN

/* Return the CFTypeID for CGPathRefs. */

CG_EXTERN CFTypeID CGPathGetTypeID(void);

/* Create a mutable path. */

CG_EXTERN CGMutablePathRef CGPathCreateMutable(void);

/* Create a copy of `path'. */

CG_EXTERN CGPathRef CGPathCreateCopy(CGPathRef path);

/* Create a mutable copy of `path'. */

CG_EXTERN CGMutablePathRef CGPathCreateMutableCopy(CGPathRef path);

/* Equivalent to `CFRetain(path)', except it doesn't crash (as CFRetain
 * does) if `path' is NULL. */

CG_EXTERN CGPathRef CGPathRetain(CGPathRef path);

/* Equivalent to `CFRelease(path)', except it doesn't crash (as CFRelease
 * does) if `path' is NULL. */

CG_EXTERN void CGPathRelease(CGPathRef path);

/* Return true if `path1' is equal to `path2'; false otherwise. */

CG_EXTERN bool CGPathEqualToPath(CGPathRef path1, CGPathRef path2);

/*** Path construction functions. ***/

/* Move the current point to `(x, y)' in `path' and begin a new subpath.
 * If `m' is non-NULL, then transform `(x, y)' by `m' first. */

CG_EXTERN void CGPathMoveToPoint(CGMutablePathRef path, const CGAffineTransform *m, float x, float y);

/* Append a straight line segment from the current point to `(x, y)' in
 * `path' and move the current point to `(x, y)'.  If `m' is non-NULL, then
 * transform `(x, y)' by `m' first. */

CG_EXTERN void CGPathAddLineToPoint(CGMutablePathRef path, const CGAffineTransform *m, float x, float y);

/* Append a quadratic curve from the current point to `(x, y)' with control
 * point `(cpx, cpy)' in `path' and move the current point to `(x, y)'.  If
 * `m' is non-NULL, then transform all points by `m' first. */

CG_EXTERN void CGPathAddQuadCurveToPoint(CGMutablePathRef path, const CGAffineTransform *m, float cpx, float cpy, float x, float y);

/* Append a cubic Bezier curve from the current point to `(x,y)' with
 * control points `(cp1x, cp1y)' and `(cp2x, cp2y)' in `path' and move the
 * current point to `(x, y)'. If `m' is non-NULL, then transform all points
 * by `m' first. */

CG_EXTERN void CGPathAddCurveToPoint(CGMutablePathRef path, const CGAffineTransform *m, float cp1x, float cp1y, float cp2x, float cp2y, float x, float y);

/* Append a line from the current point to the starting point of the
 * current subpath of `path' and end the subpath. */

CG_EXTERN void CGPathCloseSubpath(CGMutablePathRef path);

/*** Path construction convenience functions. ***/

/* Add `rect' to `path'. If `m' is non-NULL, then first transform `rect' by
 * `m' before adding it to `path'. */

CG_EXTERN void CGPathAddRect(CGMutablePathRef path, const CGAffineTransform *m, CGRect rect);

/* Add each rectangle specified by `rects', an array of `count' CGRects, to
 * `path'. If `m' is non-NULL, then first transform each rectangle by `m'
 * before adding it to `path'. */

CG_EXTERN void CGPathAddRects(CGMutablePathRef path, const CGAffineTransform *m, const CGRect rects[], size_t count);

/* Move to the first element of `points', an array of `count' CGPoints, and
 * append a line from each point to the next point in `points'.  If `m' is
 * non-NULL, then first transform each point by `m'. */

CG_EXTERN void CGPathAddLines(CGMutablePathRef path, const CGAffineTransform *m, const CGPoint points[], size_t count);

/* Add an arc of a circle to `path', possibly preceded by a straight line
 * segment. The arc is approximated by a sequence of cubic Bezier
 * curves. `(x, y)' is the center of the arc; `radius' is its radius;
 * `startAngle' is the angle to the first endpoint of the arc; `endAngle'
 * is the angle to the second endpoint of the arc; and `clockwise' is true
 * if the arc is to be drawn clockwise, false otherwise.  `startAngle' and
 * `endAngle' are measured in radians.  If `m' is non-NULL, then the
 * constructed Bezier curves representing the arc will be transformed by
 * `m' before they are added to `path'. */

CG_EXTERN void CGPathAddArc(CGMutablePathRef path, const CGAffineTransform *m, float x, float y, float radius, float startAngle, float endAngle, bool clockwise);

/* Add an arc of a circle to `path', possibly preceded by a straight line
 * segment.  The arc is approximated by a sequence of cubic Bezier curves.
 * `radius' is the radius of the arc.  The resulting arc is tangent to the
 * line from the current point of `path' to `(x1, y1)', and the line from
 * `(x1, y1)' to `(x2, y2)'.  If `m' is non-NULL, then the constructed
 * Bezier curves representing the arc will be transformed by `m' before
 * they are added to `path'. */

CG_EXTERN void CGPathAddArcToPoint(CGMutablePathRef path, const CGAffineTransform *m, float x1, float y1, float x2, float y2, float radius);

/* Add `path2' to `path1'. If `m' is non-NULL, then the points in `path2'
* will be transformed by `m' before they are added to `path1'.*/

CG_EXTERN void CGPathAddPath(CGMutablePathRef path1, const CGAffineTransform *m, CGPathRef path2);

/*** Path information functions. ***/

/* Return true if `path' contains no elements, false otherwise. */

CG_EXTERN bool CGPathIsEmpty(CGPathRef path);

/* Return true if `path' represents a rectangle, false otherwise. */

CG_EXTERN bool CGPathIsRect(CGPathRef path, CGRect *rect);

/* Return the current point of the current subpath of `path'.  If there is
 * no current point, then return CGPointZero. */

CG_EXTERN CGPoint CGPathGetCurrentPoint(CGPathRef path);

/* Return the bounding box of `path'.  The bounding box is the smallest
 * rectangle completely enclosing all points in the path, including control
 * points for Bezier and quadratic curves. If the path is empty, then
 * return CGRectNull. */

CG_EXTERN CGRect CGPathGetBoundingBox(CGPathRef path);

enum CGPathElementType {
    kCGPathElementMoveToPoint,
    kCGPathElementAddLineToPoint,
    kCGPathElementAddQuadCurveToPoint,
    kCGPathElementAddCurveToPoint,
    kCGPathElementCloseSubpath
};
typedef enum CGPathElementType CGPathElementType;

struct CGPathElement {
    CGPathElementType type;
    CGPoint *points;
};
typedef struct CGPathElement CGPathElement;

typedef void (*CGPathApplierFunction)(void *info, const CGPathElement *element);

CG_EXTERN void CGPathApply(CGPathRef path, void *info, CGPathApplierFunction function);

CG_EXTERN_C_END

#endif	/* CGPATH_H_ */


text:
package org.metafacture.xml;

import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;

import org.junit.Before;
import org.junit.Test;
import org.metafacture.framework.StreamReceiver;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.xml.sax.helpers.AttributesImpl;

/**
 * Tests for class {@link GenericXmlHandler}.
 *
 * @author Christoph Böhme
 *
 */
public final class GenericXMLHandlerTest {

    @Mock
    private StreamReceiver receiver;

    private GenericXmlHandler genericXmlHandler;

    private AttributesImpl attributes;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        genericXmlHandler = new GenericXmlHandler();
        genericXmlHandler.setRecordTagName("record");
        genericXmlHandler.setReceiver(receiver);
    }

    @Before
    public void createHelperObjects() {
        attributes = new AttributesImpl();
    }

    @Test
    public void shouldIgnoreElementsOutsideRecordElement() {
        genericXmlHandler.startElement("", "ignore-me", "ignore-me", attributes);

        verifyZeroInteractions(receiver);
    }

    @Test
    public void shouldEmitRecordElementAsStartAndEndRecordEvent() {
        genericXmlHandler.startElement("", "record", "record", attributes);
        genericXmlHandler.endElement("", "record", "record");

        final InOrder ordered = inOrder(receiver);
        ordered.verify(receiver).startRecord("");
        ordered.verify(receiver).endRecord();
    }

    @Test
    public void shouldEmitEmptyStringIfRecordTagHasNoIdAttribute() {
        genericXmlHandler.startElement("", "record", "record", attributes);

        verify(receiver).startRecord("");
    }

    @Test
    public void shouldEmitValueOfIdAttribute() {
        attributes.addAttribute("", "id", "id", "CDATA", "theRecordID");
        genericXmlHandler.startElement("", "record", "record", attributes);

        verify(receiver).startRecord("theRecordID");
    }

    @Test
    public void shouldEmitAttributesOnRecordElementAsLiterals() {
        attributes.addAttribute("", "attr", "attr", "CDATA", "attr-value");
        genericXmlHandler.startElement("", "record", "record", attributes);

        final InOrder ordered = inOrder(receiver);
        ordered.verify(receiver).startRecord("");
        ordered.verify(receiver).literal("attr", "attr-value");
    }

    @Test
    public void shouldEmitElementsAsStartAndEndEntityEvents() {
        genericXmlHandler.startElement("", "record", "record", attributes);
        genericXmlHandler.startElement("", "entity", "entity", attributes);
        genericXmlHandler.endElement("", "entity", "entity");

        final InOrder ordered = inOrder(receiver);
        ordered.verify(receiver).startEntity("entity");
        ordered.verify(receiver).endEntity();
    }

    @Test
    public void shouldEmitAttributesOnEntityElementAsLiterals() {
        genericXmlHandler.startElement("", "record", "record", attributes);
        attributes.addAttribute("", "attr", "attr", "CDATA", "attr-value");
        genericXmlHandler.startElement("", "entity", "entity", attributes);

        final InOrder ordered = inOrder(receiver);
        ordered.verify(receiver).startEntity("entity");
        ordered.verify(receiver).literal("attr", "attr-value");
    }

    @Test
    public void shouldEmitPCDataAsALiteralNamedValue() {
        final char[] charData = "char-data".toCharArray();
        genericXmlHandler.startElement("", "record", "record", attributes);
        genericXmlHandler.startElement("", "entity", "entity", attributes);
        genericXmlHandler.characters(charData, 0, charData.length);
        genericXmlHandler.endElement("", "entity", "entity");

        final InOrder ordered = inOrder(receiver);
        ordered.verify(receiver).startEntity("entity");
        ordered.verify(receiver).literal("value", "char-data");
    }

    @Test
    public void shouldEmitPCDataAsALiteralWithConfiguredValueTagName() {
        final String name = "data";
        genericXmlHandler.setValueTagName(name);

        final char[] charData = "char-data".toCharArray();
        genericXmlHandler.startElement("", "record", "record", attributes);
        genericXmlHandler.startElement("", "entity", "entity", attributes);
        genericXmlHandler.characters(charData, 0, charData.length);
        genericXmlHandler.endElement("", "entity", "entity");
        genericXmlHandler.endElement("", "record", "record");

        final InOrder ordered = inOrder(receiver);
        ordered.verify(receiver).startRecord("");
        ordered.verify(receiver).startEntity("entity");
        ordered.verify(receiver).literal(name, "char-data");
        ordered.verify(receiver).endEntity();
        ordered.verify(receiver).endRecord();
        ordered.verifyNoMoreInteractions();
        Mockito.verifyNoMoreInteractions(receiver);
    }

    @Test
    public void shouldEmitNamespaceOnEntityElementAndAttribute() {
        genericXmlHandler.setEmitNamespace(true);
        attributes.addAttribute("", "attr", "ns:attr", "CDATA", "attr-value");
        genericXmlHandler.startElement("", "record", "record", attributes);
        genericXmlHandler.startElement("", "entity", "ns:entity", attributes);

        final InOrder ordered = inOrder(receiver);
        ordered.verify(receiver).startEntity("ns:entity");
        ordered.verify(receiver).literal("ns:attr", "attr-value");
    }

    @Test
    public void shouldNotEncodeAttributesAsMarkedLiterals() {
        attributes.addAttribute("", "attr", "attr", "CDATA", "attr-value");
        genericXmlHandler.startElement("", "record", "record", attributes);
        genericXmlHandler.endElement("", "record", "record");

        final InOrder ordered = inOrder(receiver);
        ordered.verify(receiver).startRecord("");
        ordered.verify(receiver).literal("attr", "attr-value");
        ordered.verify(receiver).endRecord();
        ordered.verifyNoMoreInteractions();
        Mockito.verifyNoMoreInteractions(receiver);
    }

    @Test
    public void issue379_shouldEncodeAttributesAsLiteralsWithConfiguredMarker() {
        final String marker = "~";
        genericXmlHandler.setAttributeMarker(marker);

        genericXmlHandler.startElement("", "record", "record", attributes);
        attributes.addAttribute("", "authority", "authority", "CDATA", "marcrelator");
        attributes.addAttribute("", "type", "type", "CDATA", "text");
        genericXmlHandler.startElement("", "roleTerm", "roleTerm", attributes);
        final char[] charData = "Author".toCharArray();
        genericXmlHandler.characters(charData, 0, charData.length);
        genericXmlHandler.endElement("", "roleTerm", "roleTerm");
        genericXmlHandler.endElement("", "record", "record");

        final InOrder ordered = inOrder(receiver);
        ordered.verify(receiver).startRecord("");
        ordered.verify(receiver).startEntity("roleTerm");
        ordered.verify(receiver).literal(marker + "authority", "marcrelator");
        ordered.verify(receiver).literal(marker + "type", "text");
        ordered.verify(receiver).literal("value", "Author");
        ordered.verify(receiver).endEntity();
        ordered.verify(receiver).endRecord();
        ordered.verifyNoMoreInteractions();
        Mockito.verifyNoMoreInteractions(receiver);
    }

}


text:
Dockerfile for hadoop hdfs datanode and nodemanager
====================

This is the Dockerfile and necessary files to build a dockerized datanode and nodemanager, read the HOWTO to config for your cluster environment.

*This images is bases on the supervisored image of centos6 in [this repository](https://github.com/ambling/baseimage-docker), you may have to build it and tag it before further steps*


text:
package gov.sandia.cognition.math.geometry;

import gov.sandia.cognition.annotation.PublicationReference;
import gov.sandia.cognition.annotation.PublicationReferences;
import gov.sandia.cognition.annotation.PublicationType;
import gov.sandia.cognition.collection.CollectionUtil;
import gov.sandia.cognition.math.Metric;
import gov.sandia.cognition.math.matrix.Vectorizable;
import gov.sandia.cognition.math.matrix.VectorizableIndexComparator;
import gov.sandia.cognition.util.AbstractCloneableSerializable;
import gov.sandia.cognition.util.CloneableSerializable;
import gov.sandia.cognition.util.ObjectUtil;
import gov.sandia.cognition.util.Pair;
import java.util.AbstractCollection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.PriorityQueue;

/**
 * Implementation of a kd-tree.  Every node in a KDTree has a k-dimensional
 * Vectorizable point and an associated value as a generic "DataType."  The
 * At each depth in the KDTree, the KDTree partitions the Vectorizables into
 * two sets along a particular dimension according to the Vectorizable stored
 * in the node value.  The dimension used to partition at a particular depth
 * is (depth % k).  Vectorizables with values less than or equal to the
 * node-value-dimension are placed into the left subtree, and those greater
 * than the node-value-dimension are stored into the right subtree.  This
 * makes average-case nearest-neighbor lookup into a balanced KDTree with "N"
 * points of O(log(N)), rather than the typical "N" time for linear search.
 * Construction of a balanced KDTree with N points takes average-case
 * O(N log(N)).
 *
 * @param <VectorType> Type of Vectorizable, the first values
 * @param <DataType> Type of data in the Pair, the second values
 * @param <PairType> Type of Pair to use in the KDTree.
 * @author Kevin R. Dixon
 * @since 3.0
 */
@PublicationReferences(
    references={
        @PublicationReference(
            author="Andrew W. Moore",
            title="An intoductory tutorial on kd-trees",
            type=PublicationType.TechnicalReport,
            publication="University of Cambridge Computer Laboratory Technical Report No. 209",
            year=1991,
            url="http://www.autonlab.org/autonweb/14665.html?branch=1&language=2"
        )
        ,
        @PublicationReference(
            author="Wikipedia",
            title="kd-tree",
            type=PublicationType.WebPage,
            year=2009,
            url="http://en.wikipedia.org/wiki/Kd-tree"
        )
    }
)
public class KDTree<VectorType extends Vectorizable,DataType,PairType extends Pair<? extends VectorType,DataType>>
    extends AbstractCollection<PairType>
    implements CloneableSerializable
{

    /**
     * Number of elements in this subtree.
     */
    protected int num;

    /**
     * VectorType,DataType value for this node of the subtree.
     */
    protected PairType value;

    /**
     * Parent of this node of the subtree.
     */
    protected KDTree<VectorType,DataType,PairType> parent;

    /**
     * Left child of this subtree
     */
    protected KDTree<VectorType,DataType,PairType> leftChild;

    /**
     * Right child of this subtree.
     */
    protected KDTree<VectorType,DataType,PairType> rightChild;

    /**
     * Comparator of this node to determine less than, greater than, or equality.
     */
    protected PairFirstVectorizableIndexComparator comparator;

    /**
     * Default constructor
     */
    public KDTree()
    {
        this( null, null, null );
        this.num = 0;
    }

    /**
     * Creates a balanced KDTree from the given points.
     * @param points
     * Points to load into the KDTree.
     */
    public KDTree(
        Collection<? extends PairType> points )
    {
        this( CollectionUtil.asArrayList(points),
            new PairFirstVectorizableIndexComparator( 0 ),
            CollectionUtil.getFirst(points).getFirst().convertToVector().getDimensionality(),
            null );
    }

    /**
     * Creates a KDTree subtree for recursion purposes.
     * @param value
     * Value of the head of the subtree.
     * @param comparator
     * Comparator to use for the Vectorizables.
     * @param parent
     * Parent node of this subtree.
     */
    protected KDTree(
        PairType value,
        PairFirstVectorizableIndexComparator comparator,
        KDTree<VectorType,DataType,PairType> parent )
    {
        this.num = 1;
        this.value = value;
        this.comparator = comparator;
        this.parent = parent;
        this.leftChild = null;
        this.rightChild = null;
    }

    /**
     * Creates a balanced KDTree subtree for recursion purposes from the given
     * ArrayList of points.
     * This is an O(n log n) operation for "n" points because we use a clever
     * linear-time kth selection algorithm in CollectionUtil.findKthLargest().
     * @param points
     * Points to load into the subtree.
     * @param dimensionality
     * Dimensionality of the Vectorizables.
     * @param comparator
     * Comparator to use for the Vectorizables.
     * @param parent
     * Parent node of this subtree.
     */
    protected KDTree(
        ArrayList<? extends PairType> points,
        PairFirstVectorizableIndexComparator comparator,
        int dimensionality,
        KDTree<VectorType,DataType,PairType> parent )
    {

        this.parent = parent;
        this.comparator = comparator;
        this.num = points.size();
        if( num <= 0 )
        {
            throw new IllegalArgumentException( "No points!" );
        }
        else if( num == 1 )
        {
            this.value = points.get(0);
        }
        else
        {
            final int medianIndex = this.num / 2;
            int[] indices = CollectionUtil.findKthLargest(
                medianIndex, points, comparator );

            // This is the median of the axis.
            this.value = points.get( indices[medianIndex] );

            final int childAxis = (this.comparator.comparator.getIndex()+1) % dimensionality;
            PairFirstVectorizableIndexComparator childComparator =
                new PairFirstVectorizableIndexComparator( childAxis );

            // Left child recursion
            final int leftNum = medianIndex;
            if( leftNum > 0 )
            {
                ArrayList<PairType> leftPoints =
                    new ArrayList<PairType>( leftNum );
                for( int i = 0; i < leftNum; i++ )
                {
                    leftPoints.add( points.get( indices[i] ) );
                }
                this.leftChild = new KDTree<VectorType,DataType,PairType>(
                    leftPoints, childComparator, dimensionality, this );
            }

            // Right child recursion
            final int rightNum = num-medianIndex-1;
            if( rightNum > 0 )
            {
                ArrayList<PairType> rightPoints =
                    new ArrayList<PairType>( rightNum );
                for( int i = medianIndex+1; i < this.num; i++ )
                {
                    rightPoints.add( points.get( indices[i] ) );
                }
                this.rightChild = new KDTree<VectorType,DataType,PairType>(
                    rightPoints, childComparator, dimensionality, this );
            }

        }

    }

    @Override
    @SuppressWarnings("unchecked")
    public KDTree<VectorType,DataType,PairType> clone()
    {
        KDTree<VectorType,DataType,PairType> clone;
        try
        {
            clone = (KDTree<VectorType,DataType,PairType>) super.clone();
            clone.leftChild = ObjectUtil.cloneSafe(this.leftChild);
            clone.rightChild = ObjectUtil.cloneSafe(this.rightChild);
            clone.value = ObjectUtil.cloneSmart(this.value);
            clone.parent = this.parent;
            clone.comparator = this.comparator;
        }
        catch (CloneNotSupportedException ex)
        {
            clone = null;
        }

        return clone;

    }

    /**
     * Creates a balanced KDTree based on the given collection of Pairs.
     * This is an O(n log n) operation for "n" points because we use a clever
     * linear-time kth selection algorithm in CollectionUtil.findKthLargest().
     *
     * @param <VectorType> Type of Vectorizable, the first values.
     * @param <DataType> Type of data in the Pair, the second values.
     * @param <PairType> Type of Pair to use in the KDTree.
     * @param points Points to load into the tree.
     * @return
     * Balanced KDTree that contains all the given points.
     */
    public static <VectorType extends Vectorizable,DataType,PairType extends Pair<? extends VectorType,DataType>>
            KDTree<VectorType,DataType,PairType> createBalanced(
                Collection<? extends PairType> points )
    {
        return new KDTree<VectorType,DataType,PairType>( points );
    }

    /**
     * Rebalances the KDTree.  Does not modify this KDTree.
     * @return
     * Balanced representation of this KDTree.
     */
    public KDTree<VectorType,DataType,PairType> reblanace()
    {
        return createBalanced( this );
    }

    @Override
    public boolean add(
        PairType point )
    {

        if( this.value == null )
        {
            this.num = 1;
            this.value = point;
            this.comparator = new PairFirstVectorizableIndexComparator(0);
        }
        else
        {
            this.num++;
            int comparison = this.comparator.compare(point,this.value);
            if( comparison <= 0 )
            {
                if( this.leftChild == null )
                {
                    int dimension = point.getFirst().convertToVector().getDimensionality();
                    int childAxis = (this.comparator.comparator.getIndex() + 1) % dimension;
                    PairFirstVectorizableIndexComparator childComparator =
                        new PairFirstVectorizableIndexComparator( childAxis );
                    this.leftChild = new KDTree<VectorType,DataType,PairType>(
                        point, childComparator, this );
                }
                else
                {
                    this.leftChild.add( point );
                }
            }
            else
            {
                if( this.rightChild == null )
                {
                    int dimension = point.getFirst().convertToVector().getDimensionality();
                    int childAxis = (this.comparator.comparator.getIndex() + 1) % dimension;
                    PairFirstVectorizableIndexComparator childComparator =
                        new PairFirstVectorizableIndexComparator( childAxis );
                    this.rightChild = new KDTree<VectorType,DataType,PairType>(
                        point, childComparator, this );
                }
                else
                {
                    this.rightChild.add( point );
                }
            }
        }

        return true;

    }

    @Override
    public int size()
    {
        return this.num;
    }

    /**
     * Iterates through the KDTree using "inorder", also known as "symmetric
     * traversal", of the tree.  That is, the recursion proceeds as
     * traverse the left subtree, visit the node, traverse the right subtree.
     * @return
     * Inorder iterator of the KDTree.
     */
    @PublicationReference(
        author="Wikipedia",
        title="Tree traversal",
        type=PublicationType.WebPage,
        year=2009,
        url="http://en.wikipedia.org/wiki/Tree_traversal#Traversal"
    )
    @Override
    public Iterator<PairType> iterator()
    {
        return new InOrderKDTreeIterator<VectorType,DataType,PairType>( this );
    }

    @Override
    public String toString()
    {
        return this.toString( "Head->" );
    }

    /**
     * Recursively prints out the tree "inorder" by printing out the left
     * subtree, then the node, then the right subtree.
     * @param prefix
     * Prefix to tack onto the recursion values.
     * @return
     * String representation of the KDTree.
     */
    protected String toString(
        String prefix )
    {

        String retval = prefix + " (" + this.value.getFirst() + " -> " + this.value.getSecond() + ")\n";

        if( this.leftChild != null )
        {
            retval += this.leftChild.toString( prefix + "L" );
        }

        if( this.rightChild != null )
        {
            retval += this.rightChild.toString( prefix + "R" );
        }

        return retval;

    }

    /**
     * Finds the "num" nearest neighbors to the given "key" stored in the
     * KDTree.
     * @param key
     * Vector to find the nearest neighbors of.
     * @param k
     * Number of neighbors to find.
     * @param metric
     * Metric to use to evaluate the nearness of other points.
     * @return
     * Collection of nearest points to the "key" query.  If "num" is greater
     * than or equal to the number of points in the KDTRee, then the KDTree
     * is returned.
     */
    public Collection<PairType> findNearest(
        VectorType key,
        int k,
        Metric<? super VectorType> metric )
    {

        if( k < this.size() )
        {
            Neighborhood<VectorType,DataType,PairType> neighborhood =
                new Neighborhood<VectorType, DataType, PairType>( k );
            this.findNearest(key, k, neighborhood, metric );
            return neighborhood;
        }
        else
        {
            return this;
        }

    }

    /**
     * Finds the "num" nearest neighbors to the given "key" stored in the
     * KDTree.
     * @param key
     * Vector to find the nearest neighbors of.
     * @param k
     * Number of neighbors to find.
     * @param neighborhood
     * PriorityQueue to store the current nearest neighbors.
     * @param metric
     * Metric to use to evaluate the nearness of other points.
     */
    protected void findNearest(
        VectorType key,
        int k,
        Neighborhood<VectorType,DataType,PairType> neighborhood,
        Metric<? super VectorType> metric )
    {

        KDTree<VectorType,DataType,PairType> closer = null;
        KDTree<VectorType,DataType,PairType> further = null;

        // If we've got children, then see which child is closer
        if( (this.leftChild != null) || (this.rightChild != null) )
        {
            int comparison = this.comparator.comparator.compare(
                key, this.value.getFirst() );

            if( comparison <= 0 )
            {
                closer = this.leftChild;
                further = this.rightChild;
            }
            else
            {
                closer = this.rightChild;
                further = this.leftChild;
            }

            // recurse into the closer subtree if it exists.
            if( closer != null )
            {
                closer.findNearest(key, k, neighborhood, metric);
            }

        }

        // If there's space in the queue, then add our value.
        if( !neighborhood.isFull() )
        {
            // Compute our distance to the key
            double distance = metric.evaluate( this.value.getFirst(), key );
            neighborhood.add( this.value, distance );

            // If there's still space, then recurse to the further tree.
            if( further != null )
            {
//                if( !neighborhood.isFull() )
                {
                    further.findNearest(key, k, neighborhood, metric);
//                    further.findNearest(key, num, neighborhood, metric);
                }
            }

        }

        // The queue is full, so we need to see if we're closer than
        // the furthest neighbor.
        else
        {

            // We need to see if it's possible that the BOTH us and the
            // further subtree could contain a better point than the furthest
            // neighbor so far.
            double minimumDistance = this.computeMinimumDifference(key);
            if( minimumDistance < neighborhood.getFurthestNeighborDistance() )
            {
                double distance = metric.evaluate( this.value.getFirst(), key );
                neighborhood.offer( this.value, distance );
                if( further != null )
                {
                    further.findNearest(key, num, neighborhood, metric);
                }

            }
        }

    }

    /**
     * Computes the minimum absolute difference between the given key and
     * the "first" value stored in this subtree for the index given by
     * the embedded comparator.  That is, the minimum distance
     * "this is done by intersecting the splitting hyperplane with a hypersphere
     * around the search node [key] that has a radius equal to the current
     * nearest distance. Since the hyperplanes are all axis-aligned this is
     * implemented as a simple comparison to see whether the difference between
     * the splitting coordinate and the search point is less than the distance
     * from the search point to the current best."
     * @param key
     * Vector to compare against.
     * @return
     * Minimum absolute difference for the given index between the key and
     * the first value stored in this subtree.
     */
    protected double computeMinimumDifference(
        VectorType key )
    {
        int index = this.comparator.comparator.getIndex();
        double delta = key.convertToVector().getElement(index) -
            this.value.getFirst().convertToVector().getElement(index);
        return Math.abs( delta );
    }

    /**
     * Comparator for Pairs that have a Vectorizable as its first parameter.
     */
    protected static class PairFirstVectorizableIndexComparator
        extends AbstractCloneableSerializable
        implements Comparator<Pair<? extends Vectorizable,?>>
    {

        /**
         * Embedded comparator for the Vectorizable argument.
         */
        public VectorizableIndexComparator comparator;

        /**
         * Creates a new instance of PairFirstVectorizableIndexComparator
         * @param index
         * Index of the Vectorizable to compare against.
         */
        public PairFirstVectorizableIndexComparator(
            int index )
        {
            this.comparator = new VectorizableIndexComparator( index );
        }

        public int compare(
            Pair<? extends Vectorizable, ?> o1,
            Pair<? extends Vectorizable, ?> o2 )
        {
            return this.comparator.compare( o1.getFirst(), o2.getFirst() );
        }

    }

    /**
     * Iterates through the KDTree using "inorder", also known as "symmetric
     * traversal", of the tree.  That is, the recursion proceeds as
     * traverse the left subtree, visit the node, traverse the right subtree.
     * @param <VectorType> Type of Vectorizable, the first values
     * @param <DataType> Type of data in the Pair, the second values
     * @param <PairType> Type of Pair to use in the KDTree.
     */
    @PublicationReference(
        author="Wikipedia",
        title="Tree traversal",
        type=PublicationType.WebPage,
        year=2009,
        url="http://en.wikipedia.org/wiki/Tree_traversal#Traversal"
    )
    protected static class InOrderKDTreeIterator<VectorType extends Vectorizable,DataType,PairType extends Pair<? extends VectorType,DataType>>
        implements Iterator<PairType>
    {

        /**
         * Value of the node
         */
        public PairType nodeValue;

        /**
         * Iterator for the left subtree.
         */
        public InOrderKDTreeIterator<VectorType,DataType,PairType> leftIterator;

        /**
         * Iterator for the right subtree.
         */
        public InOrderKDTreeIterator<VectorType,DataType,PairType> rightIterator;

        /**
         * Creates a new instance of InOrderKDTreeIterator
         * @param node
         * Node from which to iterate.
         */
        public InOrderKDTreeIterator(
            KDTree<VectorType,DataType,PairType> node )
        {
            if( node.leftChild != null )
            {
                this.leftIterator = new InOrderKDTreeIterator<VectorType,DataType,PairType>( node.leftChild );
            }
            if( node.rightChild != null )
            {
                this.rightIterator = new InOrderKDTreeIterator<VectorType,DataType,PairType>( node.rightChild );
            }

            this.nodeValue = node.value;

        }

        public boolean hasNext()
        {
            return (this.nodeValue != null) ||
                ((this.rightIterator != null) && (this.rightIterator.hasNext())) ||
                ((this.leftIterator != null) && (this.leftIterator.hasNext()));
        }

        public PairType next()
        {

            PairType retval = null;

            if( (this.leftIterator != null)
                && this.leftIterator.hasNext() )
            {
                retval = this.leftIterator.next();
            }
            else
            {
                this.leftIterator = null;

                if( this.nodeValue != null )
                {
                    retval = this.nodeValue;
                    this.nodeValue = null;
                }
                else if( this.rightIterator != null )
                {
                    if( this.rightIterator.hasNext() )
                    {
                        retval = this.rightIterator.next();
                    }
                    else
                    {
                        this.rightIterator = null;
                    }
                }
            }

            if( retval == null )
            {
                throw new IllegalArgumentException(
                    "Should not have called null since we have no values to iterate!" );
            }

            return retval;

        }

        public void remove()
        {
            throw new UnsupportedOperationException("Not supported yet.");
        }

    }

    /**
     * A Collection of nearby pairs.
     * @param <VectorType> Type of Vectorizable.
     * @param <DataType> Type of output data.
     * @param <PairType> Type of Pair.
     */
    protected static class Neighborhood<VectorType extends Vectorizable, DataType, PairType extends Pair<? extends VectorType,DataType>>
        extends AbstractCollection<PairType>
    {

        /**
         * Maximum number of Neighbors in the Neighborhood.
         */
        private int k;

        /**
         * PriorityQueue to store the neighbors.
         */
        PriorityQueue<Neighbor<VectorType,DataType,PairType>> priorityQueue;

        /**
         * Creates a new Neighborhood.
         * @param k
         * Maximum number of Neighbors in the Neighborhood.
         */
        public Neighborhood(
            int k )
        {
            this.priorityQueue =
                new PriorityQueue<Neighbor<VectorType, DataType, PairType>>(k);
            this.k = k;
        }

        /**
         * Returns true if the Neighborhood is full.
         * @return
         * True if the Neighborhood is full, false if not full.
         */
        public boolean isFull()
        {
            return this.size() >= this.k;
        }

        /**
         * Returns the distance of the furthest Neighbor.
         * @return
         * Distance of the furthest Neighbor.
         */
        public double getFurthestNeighborDistance()
        {
            return this.priorityQueue.peek().distance;
        }

        /**
         * Adds the neighbor to the priority queue.
         * @param value
         * Value to add.
         * @param distance
         * Distance to associate with the neighbor to the queue.
         */
        public void add(
            PairType value,
            double distance )
        {

            while( this.isFull() )
            {
                this.priorityQueue.remove();
            }

            this.priorityQueue.add(
                new Neighbor<VectorType,DataType,PairType>(value,distance) );

        }

        /**
         * Offers the neighbor if there is space or it's closer than the
         * furthest neighbor.
         * @param value
         * Value of the neighbor.
         * @param distance
         * Distance to the key value.
         * @return
         * True if added, false if not added.
         */
        public boolean offer(
            PairType value,
            double distance )
        {

            // If we're full, then see if we're closer than the furthest
            // neighbor.
            if( this.isFull() )
            {
                if( distance < this.getFurthestNeighborDistance() )
                {
                    this.priorityQueue.remove();
                }
            }

            // If we find there is space, then add the new neighbor.
            if( !this.isFull() )
            {
                this.add( value, distance );
                return true;
            }
            else
            {
                return false;
            }

        }

        @Override
        public Iterator<PairType> iterator()
        {
            return new NeighborhoodIterator();
        }

        @Override
        public int size()
        {
            return this.priorityQueue.size();
        }

        /**
         * Holds neighbor information used during the evaluate method and is put
         * into a priority queue.
         * @param <VectorType> Type of Vectorizable, the first values
         * @param <DataType> Type of data in the Pair, the second values
         * @param <PairType> Type of Pair to use in the KDTree.
         */
        protected class Neighbor<VectorType extends Vectorizable, DataType, PairType extends Pair<? extends VectorType,DataType>>
            extends AbstractCloneableSerializable
            implements Comparable<Neighbor<VectorType, DataType, PairType>>
        {
            // Note: This class does not follow the get/set pattern in order to
            // make it as fast as possible, because it is used within the evaluate
            // method. Also, its a private internal class, so no one else should
            // use it.

            /**
             * Pair to store.
             */
            PairType pair;

            /**
             * Distance associated with this value.
             */
            private double distance;

            /**
             * Creates a new neighbor.
             *
             * @param   value
             *      The value associated with the neighbor.
             * @param distance
             * Distance associated with this value.
             */
            public Neighbor(
                final PairType value,
                final double distance)
            {
                this.pair = value;
                this.distance = distance;
            }

            public int compareTo(
                final Neighbor<VectorType, DataType, PairType> other)
            {
                // We reverse the comparison so that the item at the head of the
                // priority queue is the furthest neighbor
                return -Double.compare(this.distance, other.distance);
            }

            @Override
            @SuppressWarnings("unchecked")
            public boolean equals(
                Object obj)
            {

                if( obj == null )
                {
                    return false;
                }
                else if( obj instanceof Neighbor )
                {
                    return ((Neighbor<?,?,?>) obj).pair.getFirst().convertToVector().equals(
                        this.pair.getFirst().convertToVector() );
                }
                else
                {
                    return false;
                }

            }

            @Override
            public int hashCode()
            {
                return this.pair.getFirst().hashCode();
            }

        }

        /**
         * Iterator for the Neighborhood.
         */
        protected class NeighborhoodIterator
            implements Iterator<PairType>
        {

            /**
             * PriorityQueue iterator.
             */
            Iterator<Neighbor<VectorType,DataType,PairType>> priorityQueueIterator;

            /**
             * Default constructor.
             */
            public NeighborhoodIterator()
            {
                this.priorityQueueIterator = priorityQueue.iterator();
            }

            public boolean hasNext()
            {
                return this.priorityQueueIterator.hasNext();
            }

            public PairType next()
            {
                Neighbor<VectorType,DataType,PairType> next =
                    this.priorityQueueIterator.next();
                return next.pair;
            }

            public void remove()
            {
                throw new UnsupportedOperationException("Not supported yet.");
            }

        }

    }

}


text:
class AddTestTypeToTestCase < ActiveRecord::Migration
  def self.up
    add_column :test_cases, :test_type_id, :integer
  end

  def self.down
    remove_column :test_cases, :test_type_id
  end
end


text:
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/moduleparam.h>
#include <linux/pci_ids.h>
#include <linux/module.h>
#include <sound/core.h>
#include <sound/initval.h>
#include "ctatc.h"
#include "cthardware.h"

MODULE_AUTHOR("Creative Technology Ltd");
MODULE_DESCRIPTION("X-Fi driver version 1.03");
MODULE_LICENSE("GPL v2");
MODULE_SUPPORTED_DEVICE("{{Creative Labs, Sound Blaster X-Fi}");

static unsigned int reference_rate = 48000;
static unsigned int multiple = 2;
MODULE_PARM_DESC(reference_rate, "Reference rate (default=48000)");
module_param(reference_rate, uint, S_IRUGO);
MODULE_PARM_DESC(multiple, "Rate multiplier (default=2)");
module_param(multiple, uint, S_IRUGO);

static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;
static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR;
static bool enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP;
static unsigned int subsystem[SNDRV_CARDS];

module_param_array(index, int, NULL, 0444);
MODULE_PARM_DESC(index, "Index value for Creative X-Fi driver");
module_param_array(id, charp, NULL, 0444);
MODULE_PARM_DESC(id, "ID string for Creative X-Fi driver");
module_param_array(enable, bool, NULL, 0444);
MODULE_PARM_DESC(enable, "Enable Creative X-Fi driver");
module_param_array(subsystem, int, NULL, 0444);
MODULE_PARM_DESC(subsystem, "Override subsystem ID for Creative X-Fi driver");

static DEFINE_PCI_DEVICE_TABLE(ct_pci_dev_ids) = {
	/* only X-Fi is supported, so... */
	{ PCI_DEVICE(PCI_VENDOR_ID_CREATIVE, PCI_DEVICE_ID_CREATIVE_20K1),
	  .driver_data = ATC20K1,
	},
	{ PCI_DEVICE(PCI_VENDOR_ID_CREATIVE, PCI_DEVICE_ID_CREATIVE_20K2),
	  .driver_data = ATC20K2,
	},
	{ 0, }
};
MODULE_DEVICE_TABLE(pci, ct_pci_dev_ids);

static int __devinit
ct_card_probe(struct pci_dev *pci, const struct pci_device_id *pci_id)
{
	static int dev;
	struct snd_card *card;
	struct ct_atc *atc;
	int err;

	if (dev >= SNDRV_CARDS)
		return -ENODEV;

	if (!enable[dev]) {
		dev++;
		return -ENOENT;
	}
	err = snd_card_create(index[dev], id[dev], THIS_MODULE, 0, &card);
	if (err)
		return err;
	if ((reference_rate != 48000) && (reference_rate != 44100)) {
		printk(KERN_ERR "ctxfi: Invalid reference_rate value %u!!!\n",
		       reference_rate);
		printk(KERN_ERR "ctxfi: The valid values for reference_rate "
		       "are 48000 and 44100, Value 48000 is assumed.\n");
		reference_rate = 48000;
	}
	if ((multiple != 1) && (multiple != 2) && (multiple != 4)) {
		printk(KERN_ERR "ctxfi: Invalid multiple value %u!!!\n",
		       multiple);
		printk(KERN_ERR "ctxfi: The valid values for multiple are "
		       "1, 2 and 4, Value 2 is assumed.\n");
		multiple = 2;
	}
	err = ct_atc_create(card, pci, reference_rate, multiple,
			    pci_id->driver_data, subsystem[dev], &atc);
	if (err < 0)
		goto error;

	card->private_data = atc;

	/* Create alsa devices supported by this card */
	err = ct_atc_create_alsa_devs(atc);
	if (err < 0)
		goto error;

	strcpy(card->driver, "SB-XFi");
	strcpy(card->shortname, "Creative X-Fi");
	snprintf(card->longname, sizeof(card->longname), "%s %s %s",
		 card->shortname, atc->chip_name, atc->model_name);

	err = snd_card_register(card);
	if (err < 0)
		goto error;

	pci_set_drvdata(pci, card);
	dev++;

	return 0;

error:
	snd_card_free(card);
	return err;
}

static void __devexit ct_card_remove(struct pci_dev *pci)
{
	snd_card_free(pci_get_drvdata(pci));
	pci_set_drvdata(pci, NULL);
}

#ifdef CONFIG_PM
static int ct_card_suspend(struct pci_dev *pci, pm_message_t state)
{
	struct snd_card *card = pci_get_drvdata(pci);
	struct ct_atc *atc = card->private_data;

	return atc->suspend(atc, state);
}

static int ct_card_resume(struct pci_dev *pci)
{
	struct snd_card *card = pci_get_drvdata(pci);
	struct ct_atc *atc = card->private_data;

	return atc->resume(atc);
}
#endif

static struct pci_driver ct_driver = {
	.name = KBUILD_MODNAME,
	.id_table = ct_pci_dev_ids,
	.probe = ct_card_probe,
	.remove = __devexit_p(ct_card_remove),
#ifdef CONFIG_PM
	.suspend = ct_card_suspend,
	.resume = ct_card_resume,
#endif
};

static int __init ct_card_init(void)
{
	return pci_register_driver(&ct_driver);
}

static void __exit ct_card_exit(void)
{
	pci_unregister_driver(&ct_driver);
}

module_init(ct_card_init)
module_exit(ct_card_exit)


text:
// @namespace
var ARjs = ARjs || {}

// TODO this is a controls... should i give the object3d here ?
// not according to 'no three.js dependancy'

/**
 * Create an anchor in the real world
 *
 * @param {ARjs.Session} arSession - the session on which we create the anchor
 * @param {Object} markerParameters - parameter of this anchor
 */
ARjs.Anchor = function(arSession, markerParameters){
	var _this = this
	var arContext = arSession.arContext
	var scene = arSession.parameters.scene
	var camera = arSession.parameters.camera

	this.arSession = arSession
	this.parameters = markerParameters

	// log to debug
	console.log('ARjs.Anchor -', 'changeMatrixMode:', this.parameters.changeMatrixMode, '/ markersAreaEnabled:', markerParameters.markersAreaEnabled)

	var markerRoot = new THREE.Group
	scene.add(markerRoot)

	// set controlledObject depending on changeMatrixMode
	if( markerParameters.changeMatrixMode === 'modelViewMatrix' ){
		var controlledObject = markerRoot
	}else if( markerParameters.changeMatrixMode === 'cameraTransformMatrix' ){
		var controlledObject = camera
	}else console.assert(false)

	if( markerParameters.markersAreaEnabled === false ){
		var markerControls = new THREEx.ArMarkerControls(arContext, controlledObject, markerParameters)
		this.controls = markerControls
	}else{
		// sanity check - MUST be a trackingBackend with markers
		console.assert( arContext.parameters.trackingBackend === 'artoolkit' )

		// honor markers-page-resolution for https://webxr.io/augmented-website
		if( location.hash.substring(1).startsWith('markers-page-resolution=') === true ){
			// get resolutionW/resolutionH from url
			var markerPageResolution = location.hash.substring(1)
			var matches = markerPageResolution.match(/markers-page-resolution=(\d+)x(\d+)/)
			console.assert(matches.length === 3)
			var resolutionW = parseInt(matches[1])
			var resolutionH = parseInt(matches[2])
			var arContext = arSession.arContext
			// generate and store the ARjsMultiMarkerFile
			ARjs.MarkersAreaUtils.storeMarkersAreaFileFromResolution(arContext.parameters.trackingBackend, resolutionW, resolutionH)
		}

		// if there is no ARjsMultiMarkerFile, build a default one
		if( localStorage.getItem('ARjsMultiMarkerFile') === null ){
			ARjs.MarkersAreaUtils.storeDefaultMultiMarkerFile(arContext.parameters.trackingBackend)
		}

		// get multiMarkerFile from localStorage
		console.assert( localStorage.getItem('ARjsMultiMarkerFile') !== null )
		var multiMarkerFile = localStorage.getItem('ARjsMultiMarkerFile')

		// set controlledObject depending on changeMatrixMode
		if( markerParameters.changeMatrixMode === 'modelViewMatrix' ){
			var parent3D = scene
		}else if( markerParameters.changeMatrixMode === 'cameraTransformMatrix' ){
			var parent3D = camera
		}else console.assert(false)

		// build a multiMarkerControls
		var multiMarkerControls = ARjs.MarkersAreaControls.fromJSON(arContext, parent3D, controlledObject, multiMarkerFile)
		this.controls = multiMarkerControls

		// honor markerParameters.changeMatrixMode
		multiMarkerControls.parameters.changeMatrixMode = markerParameters.changeMatrixMode

// TODO put subMarkerControls visibility into an external file. with 2 handling for three.js and babylon.js
		// create ArMarkerHelper - useful to debug - super three.js specific
		var markerHelpers = []
		multiMarkerControls.subMarkersControls.forEach(function(subMarkerControls){
			// add an helper to visuable each sub-marker
			var markerHelper = new THREEx.ArMarkerHelper(subMarkerControls)
			markerHelper.object3d.visible = false
			// subMarkerControls.object3d.add( markerHelper.object3d )
			subMarkerControls.object3d.add( markerHelper.object3d )
			// add it to markerHelpers
			markerHelpers.push(markerHelper)
		})
		// define API specific to markersArea
		this.markersArea = {}
		this.markersArea.setSubMarkersVisibility = function(visible){
			markerHelpers.forEach(function(markerHelper){
				markerHelper.object3d.visible = visible
			})
		}
	}

	this.object3d = new THREE.Group()

	//////////////////////////////////////////////////////////////////////////////
	//		THREEx.ArSmoothedControls
	//////////////////////////////////////////////////////////////////////////////

	var shouldBeSmoothed = true

	if( shouldBeSmoothed === true ){
		// build a smoothedControls
		var smoothedRoot = new THREE.Group()
		scene.add(smoothedRoot)
		var smoothedControls = new THREEx.ArSmoothedControls(smoothedRoot)
		smoothedRoot.add(this.object3d)
	}else{
		markerRoot.add(this.object3d)
	}

	//////////////////////////////////////////////////////////////////////////////
	//		Code Separator
	//////////////////////////////////////////////////////////////////////////////
	this.update = function(){
		// update _this.object3d.visible
		_this.object3d.visible = _this.object3d.parent.visible

		// console.log('controlledObject.visible', _this.object3d.parent.visible)
		if( smoothedControls !== undefined ){
			// update smoothedControls parameters depending on how many markers are visible in multiMarkerControls
			if( multiMarkerControls !== undefined ){
				multiMarkerControls.updateSmoothedControls(smoothedControls)
			}

			// update smoothedControls
			smoothedControls.update(markerRoot)
		}
	}
}


text:
package com.esri.gpt.framework.resource.query;

/**
 * Query. Provides a way of obtaining a list matching metadata records from the
 * remote repository. Typically, instance of the concrete implementation can be
 * created through {@link QueryBuilder#newQuery(Criteria)}.
 * @see QueryBuilder
 */
public interface Query {

/**
 * Executes query.
 */
Result execute();
}


text:
using namespace mlir;

namespace {
struct PrintOpStatsPass : public ModulePass<PrintOpStatsPass> {
  explicit PrintOpStatsPass(llvm::raw_ostream &os = llvm::errs()) : os(os) {}

  // Prints the resultant operation statistics post iterating over the module.
  void runOnModule() override;

  // Print summary of op stats.
  void printSummary();

private:
  llvm::StringMap<int64_t> opCount;
  llvm::raw_ostream &os;
};
} // namespace

void PrintOpStatsPass::runOnModule() {
  opCount.clear();

  // Compute the operation statistics for each function in the module.
  for (auto &op : getModule())
    op.walk([&](Operation *op) { ++opCount[op->getName().getStringRef()]; });
  printSummary();
}

void PrintOpStatsPass::printSummary() {
  os << "Operations encountered:\n";
  os << "-----------------------\n";
  SmallVector<StringRef, 64> sorted(opCount.keys());
  llvm::sort(sorted);

  // Split an operation name from its dialect prefix.
  auto splitOperationName = [](StringRef opName) {
    auto splitName = opName.split('.');
    return splitName.second.empty() ? std::make_pair("", splitName.first)
                                    : splitName;
  };

  // Compute the largest dialect and operation name.
  StringRef dialectName, opName;
  size_t maxLenOpName = 0, maxLenDialect = 0;
  for (const auto &key : sorted) {
    std::tie(dialectName, opName) = splitOperationName(key);
    maxLenDialect = std::max(maxLenDialect, dialectName.size());
    maxLenOpName = std::max(maxLenOpName, opName.size());
  }

  for (const auto &key : sorted) {
    std::tie(dialectName, opName) = splitOperationName(key);

    // Left-align the names (aligning on the dialect) and right-align the count
    // below. The alignment is for readability and does not affect CSV/FileCheck
    // parsing.
    if (dialectName.empty())
      os.indent(maxLenDialect + 3);
    else
      os << llvm::right_justify(dialectName, maxLenDialect + 2) << '.';

    // Left justify the operation name.
    os << llvm::left_justify(opName, maxLenOpName) << " , " << opCount[key]
       << '\n';
  }
}

static PassRegistration<PrintOpStatsPass>
    pass("print-op-stats", "Print statistics of operations");


text:
package com.kondasamy.soapui.plugins.exportResponseGroovy;

import java.lang.*;
import java.io.*;
import java.net.*;
import java.util.*;
import groovy.lang.*;
import groovy.util.*;

public class TestCaseSaveResponseAction
  extends com.eviware.soapui.support.action.support.AbstractSoapUIAction<com.eviware.soapui.model.testsuite.TestCase>  implements
    groovy.lang.GroovyObject {
public TestCaseSaveResponseAction
() {
super ((java.lang.String)null);
}
public  groovy.lang.MetaClass getMetaClass() { return (groovy.lang.MetaClass)null;}
public  void setMetaClass(groovy.lang.MetaClass mc) { }
public  java.lang.Object invokeMethod(java.lang.String method, java.lang.Object arguments) { return null;}
public  java.lang.Object getProperty(java.lang.String property) { return null;}
public  void setProperty(java.lang.String property, java.lang.Object value) { }
@java.lang.Override() public  void perform(com.eviware.soapui.model.testsuite.TestCase testCase, java.lang.Object o) { }
}


text:
package org.scalawiki.wlx.dto

import org.scalawiki.wlx.dto.Koatuu.betterName
import play.api.libs.functional.syntax._
import play.api.libs.json.Reads._
import play.api.libs.json._

object KoatuuNew {

  val readStringFromLong: Reads[String] = implicitly[Reads[Long]].map(x => x.toString)

  def stringOrLong(name: String): Reads[String] = {
    (__ \ name).read[String] or
      (__ \ name).read[String](readStringFromLong)
  }

  implicit val regionReads: Reads[AdmDivisionFlat] = (
    stringOrLong("Перший рівень") and
      stringOrLong("Другий рівень") and
      stringOrLong("Третій рівень") and
      stringOrLong("Четвертий рівень") and
      (__ \ "Назва об'єкта українською мовою").read[String].map(betterName) and
      (__ \ "Категорія").readNullable[String].map(_.flatMap(KoatuuTypes.codeToType.get))
    ) (AdmDivisionFlat.apply(_, _, _, _, _, _))

  def parse(json: JsValue): Seq[AdmDivisionFlat] = {
    json.as[Seq[AdmDivisionFlat]]
  }

}


text:
'use strict';

var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default'];

Object.defineProperty(exports, '__esModule', {
  value: true
});
exports['default'] = componentDocblockHandler;

var _recast = require('recast');

var _recast2 = _interopRequireDefault(_recast);

var _utilsDocblock = require('../utils/docblock');

var types = _recast2['default'].types.namedTypes;

function isClassDefinition(nodePath) {
  var node = nodePath.node;
  return types.ClassDeclaration.check(node) || types.ClassExpression.check(node);
}

/**
 * Finds the nearest block comment before the component definition.
 */

function componentDocblockHandler(documentation, path) {
  var description = null;
  // Find parent statement (e.g. var Component = React.createClass(<path>);)
  var searchPath = path;
  while (searchPath && !types.Statement.check(searchPath.node)) {
    searchPath = searchPath.parent;
  }
  if (searchPath) {
    // Class declarations are statements but can be part of default
    // export declarations
    if (types.ClassDeclaration.check(searchPath.node) && types.ExportDefaultDeclaration.check(searchPath.parentPath.node)) {
      searchPath = searchPath.parentPath;
    }
    // If the parent is an export statement, we have to traverse one more up
    if (types.ExportNamedDeclaration.check(searchPath.parentPath.node)) {
      searchPath = searchPath.parentPath;
    }
    description = (0, _utilsDocblock.getDocblock)(searchPath);
  }
  if (description == null && isClassDefinition(path)) {
    // If we have a class declaration or expression, then the comment might be
    // attached to the first decorator instead.
    if (path.node.decorators && path.node.decorators.length > 0) {
      description = (0, _utilsDocblock.getDocblock)(path.get('decorators', 0));
    }
  }
  if (description == null) {
    // If this is the first statement in the module body, the comment is attached
    // to the program node
    var programPath = searchPath;
    while (programPath && !types.Program.check(programPath.node)) {
      programPath = programPath.parent;
    }
    if (programPath.get('body', 0) === searchPath) {
      description = (0, _utilsDocblock.getDocblock)(programPath);
    }
  }
  documentation.set('description', description || '');
}

module.exports = exports['default'];


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Nova Acta R. Soc. Scient. upsal. , Ser. 4 8(1. 2): 306 (1932)

#### Original name
Encoeliopsis rhododendri var. rhododendri

### Remarks
null


text:
namespace euphoria::runner
{
    struct BoundVar
    {
        std::string name;
        float state;
        float last_state;
        core::Key key;

        BoundVar(const std::string& n, const core::Key& k);

        // todo(Gustav): figure out how to bind keys to this property
        // todo(Gustav): figure out how to handle just pressed
        // todo(Gustav): figure out how to handle player characters
        // todo(Gustav): figure out how to handle inputs other than keyboard
    };

    struct InputSystem
    {
    public:
        static void
        bind(LuaState* duk);

        void
        add(std::shared_ptr<BoundVar> bind);

        void
        set_key_state(core::Key key, float state);

        void
        set(sol::table* container) const;

        void
        update_state();

    private:
        std::vector<std::shared_ptr<BoundVar>> binds;
    };
}


text:
package de.fau.cs.mad.fablab.android.view.common.fragments;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.View;

import butterknife.ButterKnife;
import de.fau.cs.mad.fablab.android.view.activities.MainActivity;

/**
 * Base class for all Fragments
 */
public abstract class BaseFragment extends Fragment {
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        ((MainActivity) getActivity()).inject(this);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        ButterKnife.bind(this, view);
    }

    public void setDisplayOptions(int options) {
        ((MainActivity) getActivity()).setDisplayOptions(options);
    }

    public void setNavigationDrawerSelection(int menuItemId) {
        ((MainActivity) getActivity()).setNavigationDrawerSelection(menuItemId);
    }

    public void setTitle(int titleId) {
        getActivity().setTitle(titleId);
    }
}


text:
@font-face {
	font-family: 'Verlag-Book';
	src:url('Verlag-Book.otf') format("opentype");
	/*src:url('Verlag-Book/Verlag-Book.eot?d7yf1v');
	src:url('Verlag-Book/Verlag-Book.eot?') format('embedded-opentype'),
		url('Verlag-Book/Verlag-Book.woff?d7yf1v') format('woff'),
		url('Verlag-Book/Verlag-Book.ttf?d7yf1v') format('truetype');*/
	font-weight: normal;
	font-style: normal;
}

@font-face {
	font-family: 'Verlag-Book';
	src:url('Verlag-Bold.otf') format("opentype");
	/*src:url('Verlag-Book/Verlag-Bold.eot?d7yf1v');
	src:url('Verlag-Book/Verlag-Bold.eot?') format('embedded-opentype'),
		url('Verlag-Book/Verlag-Bold.woff?d7yf1v') format('woff'),
		url('Verlag-Book/Verlag-Bold.ttf?d7yf1v') format('truetype');*/
	font-weight: bold;
	font-style: normal;
}

@font-face {
	font-family: 'Slim-Joe';
	src:url('Slim+Joe.otf') format("opentype");

	font-weight: normal;
	font-style: normal;
}

@font-face {
	font-family: 'Big-John';
	src:url('BIG+JOHN.otf') format("opentype");

	font-weight: normal;
	font-style: normal;
}


text:
<?php
class Kwf_Component_Abstract_ExtConfig_Grid extends Kwf_Component_Abstract_ExtConfig_Abstract
{
    protected function _getConfig()
    {
        $ret = array(
            'grid' => $this->_getStandardConfig('kwf.autogrid')
        );
        return $ret;
    }
}


text:
<form action="account/updatePassword" method="POST">
<input name="password" type="text" class="filter_rows" placeholder="password" >
<input type="submit" value="Save Password">
<input name="id" type="hidden" value="<?php echo $id?>">
</form>


text:
class TimeDateSetUI : public UI {
  private:
    TimeProvider& timeProvider;
    ButtonsManager& buttonsManager;
    enum EDIT {
      EDIT_TIME,EDIT_AM_PM,EDIT_DATE,EDIT_YEAR
    };

    EDIT currentEdit;
    SevSeg& sevSeg;

    SRLeds& indicators;

    byte activeDigit= 1;
    byte digits[4]={0,0,0,0};

    bool isAM;
    int aggregateDigits(bool firstTwo,bool lastTwo);
    bool isValid(byte newDigits[4]) ;
    void initEditTime();
    void initEditAM_PM();
    void initEditDate();
    void initEditYear();

    void saveTime();
    void saveAM_PM();
    void saveDate();
    void saveYear();

    void initCurrentMode();
    void saveCurrentMode();
    void nextMode();
  public:
    TimeDateSetUI(TimeProvider& timeProvider,
		  ButtonsManager& buttonsManager,
		  SevSeg& sevSeg,
		  SRLeds& indicator);
    void initialize();
    void process();
    void saveData();
};


text:
package io.trane.ndbc.value;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

public final class LocalDateValue extends Value<LocalDate> {

  public LocalDateValue(final LocalDate value) {
    super(value);
  }

  @Override
  public final LocalDate getLocalDate() {
    return get();
  }

  @Override
  public LocalDateTime getLocalDateTime() {
    return LocalDateTime.of(get(), LocalTime.MIDNIGHT);
  }
}


text:
The bare bones OS image for Beaglebone Green.

# How to use this image

Systemd can be enabled by adding `ENV INITSYSTEM on` to your Dockerfile below the `FROM <Docker image>` line. This will trigger systemd init system on the Docker image.

## Create a `Dockerfile` in your app project

	FROM resin/beaglebone-green-debian:latest
	# Enable systemd
	ENV INITSYSTEM on
	# Your code goes here

You can then build and run the Docker image:

	docker build -t my-app .
	docker run -it --rm --name my-running-app my-app


text:
===
title: Design related full text feed
extends: atom.j2
listable: false
===


text:
var Q = require("q");
var uuid = require("node-uuid");

var database = require("../database.js");
var users = require("./users.js");

exports.requestResetId = function(userId) {

    var newId = uuid();

    return database.getPooledConnection()
    .then(function(connection) {
        return Q.ninvoke(connection, "query", "INSERT INTO passwordResets SET ?", [{uuid:newId, userId:userId}])
        .then(function() {
            return Q.ninvoke(connection, "query", "SELECT id FROM passwordResets WHERE userId = ? ORDER BY id DESC LIMIT 4,1", [userId, userId]);
        })
        .then(function(idCutoffResult) {

            if (idCutoffResult[0].length > 0) {
                var idCutoff = idCutoffResult[0][0].id;

                return Q.ninvoke(connection, "query", "DELETE FROM passwordResets WHERE userId = ? and id < ?", [userId, idCutoff]);
            }
        })
        .then(function() {
            return newId;
        })
        .fin(function() {
            connection.release();
        });
    });
};

exports.useResetId = function(resetId, newPassword) {

    return database.getPooledConnection()
    .then(function(connection) {
        return Q.ninvoke(connection, "query", "SELECT U.id FROM passwordResets PR JOIN users U ON U.id = PR.userId WHERE PR.uuid = ? AND PR.dateCreated > DATE_ADD(NOW(), INTERVAL -2 HOUR)", [resetId])
        .then(function(results) {

            if (results[0].length === 0) {
                return false;
            }

            var userId = results[0][0].id;

            return Q.ninvoke(connection, "query", "DELETE FROM passwordResets WHERE uuid = ?", [resetId])
            .fin(function() {
                connection.release();
            })
            .then(function() {
                return users.updateUserPassword(userId, newPassword);
            });
        });
    });
};