text:
<!--
  ~ Copyright (c) 2016-2017 Evolveum and contributors
  ~
  ~ This work is dual-licensed under the Apache License 2.0
  ~ and European Union Public License. See LICENSE file for details.
  -->
<role oid="00000000-0000-0000-0000-00000000d001"
        xmlns="http://midpoint.evolveum.com/xml/ns/public/common/common-3"
        xmlns:q="http://prism.evolveum.com/xml/ns/public/query-3"
        xmlns:t="http://prism.evolveum.com/xml/ns/public/types-3">
    <name>Universal Self Delegator</name>
    <delegable>true</delegable>
    <authorization>
        <name>authz-read-basic</name>
        <action>http://midpoint.evolveum.com/xml/ns/public/security/authorization-model-3#read</action>
        <item>name</item>
    </authorization>
    <authorization>
        <name>authz-read-self</name>
        <action>http://midpoint.evolveum.com/xml/ns/public/security/authorization-model-3#read</action>
        <object>
            <special>self</special>
        </object>
    </authorization>
    <authorization>
        <name>authz-read-delagate-assignments</name>
        <action>http://midpoint.evolveum.com/xml/ns/public/security/authorization-model-3#read</action>
        <object>
            <type>UserType</type>
            <delegator>
                <special>self</special>
            </delegator>
        </object>
        <item>assignment</item>
        <item>roleMembershipRef</item>
        <item>delegatedRef</item>
    </authorization>
    <authorization>
        <name>delegator-req</name>
        <action>http://midpoint.evolveum.com/xml/ns/public/security/authorization-model-3#delegate</action>
        <phase>request</phase>
        <object>
            <type>UserType</type>
        </object>
        <target>
            <special>self</special>
        </target>
    </authorization>
    <authorization>
        <name>delegator-exec-user</name>
        <description>
            Quite strong universal execution rights are needed here. We are going to modify other users
            (deputy assignments are in the delegate user, not delegator).
        </description>
        <action>http://midpoint.evolveum.com/xml/ns/public/security/authorization-model-3#modify</action>
        <phase>execution</phase>
        <object>
            <type>UserType</type>
        </object>
    </authorization>
    <authorization>
        <name>delegator-exec-shadow</name>
        <description>
            Quite strong universal execution rights are needed here. We are going to modify other users
            (deputy assignments are in the delegate user, not delegator). Modification of other users
            may mean also creation/modification/deletion of their accounts.
        </description>
        <action>http://midpoint.evolveum.com/xml/ns/public/security/authorization-model-3#add</action>
        <action>http://midpoint.evolveum.com/xml/ns/public/security/authorization-model-3#modify</action>
        <action>http://midpoint.evolveum.com/xml/ns/public/security/authorization-model-3#delete</action>
        <phase>execution</phase>
        <object>
            <type>ShadowType</type>
        </object>
    </authorization>
</role>


text:
import { Injectable } from '@angular/core';
import { Headers } from '@angular/http';

@Injectable()
export class GenerateHeader {
    headers: Headers;

    constructor() {
    }

    public return() {
        let currentUser = JSON.parse(localStorage.getItem('currentUser'));
        let token = currentUser && currentUser.token;
        this.headers = new Headers({
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + token
        });
        return this.headers;
    }
}

redpajama_set_name: RedPajamaGithub


text:
#include "slang_pragma_recorder.h"

#include <string>

#include "clang/Basic/TokenKinds.h"

#include "clang/Lex/Preprocessor.h"
#include "clang/Lex/Token.h"

namespace slang {

bool PragmaRecorder::GetPragmaNameFromToken(const clang::Token &Token,
                                            std::string &PragmaName) {
  if (Token.isLiteral())
    PragmaName.assign(Token.getLiteralData(), Token.getLength());
  else if (Token.is(clang::tok::identifier))
    PragmaName.assign(Token.getIdentifierInfo()->getNameStart(),
                      Token.getIdentifierInfo()->getLength());
  else
    return false;
  return true;
}

bool PragmaRecorder::GetPragmaValueFromToken(const clang::Token &Token,
                                             std::string &PragmaValue) {
  // Same as the GetPragmaName()
  if (Token.is(clang::tok::r_paren))
    PragmaValue.clear();
  else
    return GetPragmaNameFromToken(Token, PragmaValue);
  return true;
}

PragmaRecorder::PragmaRecorder(PragmaList *Pragmas)
    : PragmaHandler(),
      mPragmas(Pragmas) {
  return;
}

void PragmaRecorder::HandlePragma(clang::Preprocessor &PP,
                                  clang::PragmaIntroducerKind Introducer,
                                  clang::Token &FirstToken) {
  clang::Token &CurrentToken = FirstToken;
  std::string PragmaName, PragmaValue = "";
  // Pragma in ACC should be a name/value pair

  if (GetPragmaNameFromToken(FirstToken, PragmaName)) {
    // start parsing the value '(' PragmaValue ')', if we have one.
    const clang::Token* NextToken = &PP.LookAhead(0);

    if (NextToken->is(clang::tok::l_paren))
      PP.LexUnexpandedToken(CurrentToken);
    else
      goto end_parsing_pragma_value;

    NextToken = &PP.LookAhead(0);
    if (GetPragmaValueFromToken(*NextToken, PragmaValue)) {
      PP.Lex(CurrentToken);
    } else {
      PP.LexUnexpandedToken(CurrentToken);
      PP.Diag(NextToken->getLocation(),
              PP.getDiagnostics().getCustomDiagID(
                  clang::DiagnosticsEngine::Error,
                  "expected value after '#pragma %0('")) << PragmaName;
      return;
    }

    if (!NextToken->is(clang::tok::r_paren)) {
      NextToken = &PP.LookAhead(0);
      if (NextToken->is(clang::tok::r_paren)) {
        PP.LexUnexpandedToken(CurrentToken);
      } else {
        PP.LexUnexpandedToken(CurrentToken);
        PP.Diag(NextToken->getLocation(),
                PP.getDiagnostics().getCustomDiagID(
                    clang::DiagnosticsEngine::Error,
                    "missing ')' after '#pragma %0(%1'"))
            << PragmaName << PragmaValue;
        return;
      }
    }
  } else {
    PP.Diag(FirstToken.getLocation(),
            PP.getDiagnostics().getCustomDiagID(
                clang::DiagnosticsEngine::Error,
                "no pragma name or value"));
    return;
  }

 end_parsing_pragma_value:

  // PragmaValue may be an empty string.
  mPragmas->push_back(make_pair(PragmaName, PragmaValue));

  // Inform lex to eat the token
  PP.LexUnexpandedToken(CurrentToken);

  return;
}

}  // namespace slang


text:
<?php

namespace App\Ecofy\Modules\Account;

interface AccountServiceContract
{
    /**
     * find by email
     *
     * @param string  $email - Email to search for
     * @return Model  - Upon success, return the found model
     */
    public function findByEmail($email);

    // Resource Access Operations {{

    /**
     * Add
     *
     * @param Object  $resource - The resource (record) to add
     * @param Object  $options  - Any options for add operation
     * @return Model  - Upon success, return the added model
     */
    public function add($resource, $options);

    /**
     * query
     *
     * @param Object  $criteria - The criteria for the query
     * @param Object  $options  - Any options for query operation
     * @return Array.<Model>  - Upon success, return the models
     */
    public function query($criteria, $options);

    /**
     * query
     *
     * @param Object  $criteria - The criteria for the query
     * @param Object  $options  - Any options for query operation
     * @return number  - Upon success, return count satisfying the criteria
     */
    public function count($criteria, $options);

    /**
     * Find
     *
     * @param Criteria  $criteria - The crediential object
     * @param object  $options  - Any options for find operation
     * @return Model  - Upon success the model returned
     */
    public function find($criteria, $options);

    /**
     * Find by PK
     *
     * @param mixed  $pk - The primary key of the resource to find
     * @param object  $options  - Any options for find operation
     * @return Model  - Upon success the model returned
     */
    public function findByPK($pk, $options);

    /**
     * Update
     *
     * @param Criteria  $criteria - The crediential object
     * @param object  $resource  - The resource (record) to update
     * @param object  $options  - Any options for update operation
     * @return Model  - Upon success the model returned
     */
    public function update($criteria, $resource, $options);

    /**
     * Remove
     *
     * @param Criteria  $criteria - The crediential object
     * @param object  $options  - Any options for remove operation
     * @return Model  - Upon success the model returned
     */
    public function remove($criteria, $options);

    /**
     * Remove
     *
     * @param mixed  $pk - The primary key of the resource to remove
     * @param object  $options  - Any options for remove operation
     * @return Model  - Upon success the model returned
     */
    public function removeByPK($pk, $options);

    // }} Resource Access Operations

}


text:
import './middleware'
import './proc/base'
import './proc/promise'
import './proc/take'
import './proc/put'
import './proc/call'
import './proc/context'
import './proc/cps'
import './proc/iterators'
import './proc/parallel'
import './proc/race'
import './proc/forkjoin'
import './proc/forkJoinErrors'
import './proc/logging'
import './proc/onerror'
import './proc/cancellation'
import './proc/select'
import './proc/channel'
import './proc/flush'
import './channel'
import './channel-recipes'
import './proc/takeSync'
import './runSaga'
import './monitoring'
import './sagaHelpers/takeEvery'
import './sagaHelpers/takeLatest'
import './sagaHelpers/throttle'
import './typescript';
import './utils/cloneableGenerator';


text:
package net.wasdev.twelvefactorapp;

import javax.json.JsonObject;

public class myObject {

    private JsonObject myData;

    public myObject(JsonObject data) {
        this.myData = data;
    }

    public JsonObject getData() {
        return this.myData;
    }

}


text:
#ifndef HEADER_CURL_HASH_H
#define HEADER_CURL_HASH_H

#include "curl_setup.h"

#include <stddef.h>

#include "llist.h"

/* Hash function prototype */
typedef size_t (*hash_function) (void *key,
                                 size_t key_length,
                                 size_t slots_num);

/*
   Comparator function prototype. Compares two keys.
*/
typedef size_t (*comp_function) (void *key1,
                                 size_t key1_len,
                                 void *key2,
                                 size_t key2_len);

typedef void (*Curl_hash_dtor)(void *);

struct Curl_hash {
  struct Curl_llist *table;

  /* Hash function to be used for this hash table */
  hash_function hash_func;

  /* Comparator function to compare keys */
  comp_function comp_func;
  Curl_hash_dtor   dtor;
  int slots;
  size_t size;
};

struct Curl_hash_element {
  struct Curl_llist_element list;
  void   *ptr;
  size_t key_len;
  char   key[1]; /* allocated memory following the struct */
};

struct Curl_hash_iterator {
  struct Curl_hash *hash;
  int slot_index;
  struct Curl_llist_element *current_element;
};

void Curl_hash_init(struct Curl_hash *h,
                    int slots,
                    hash_function hfunc,
                    comp_function comparator,
                    Curl_hash_dtor dtor);

void *Curl_hash_add(struct Curl_hash *h, void *key, size_t key_len, void *p);
int Curl_hash_delete(struct Curl_hash *h, void *key, size_t key_len);
void *Curl_hash_pick(struct Curl_hash *, void *key, size_t key_len);
void Curl_hash_apply(struct Curl_hash *h, void *user,
                     void (*cb)(void *user, void *ptr));
#define Curl_hash_count(h) ((h)->size)
void Curl_hash_destroy(struct Curl_hash *h);
void Curl_hash_clean(struct Curl_hash *h);
void Curl_hash_clean_with_criterium(struct Curl_hash *h, void *user,
                                    int (*comp)(void *, void *));
size_t Curl_hash_str(void *key, size_t key_length, size_t slots_num);
size_t Curl_str_key_compare(void *k1, size_t key1_len, void *k2,
                            size_t key2_len);
void Curl_hash_start_iterate(struct Curl_hash *hash,
                             struct Curl_hash_iterator *iter);
struct Curl_hash_element *
Curl_hash_next_element(struct Curl_hash_iterator *iter);

void Curl_hash_print(struct Curl_hash *h,
                     void (*func)(void *));

#endif /* HEADER_CURL_HASH_H */


text:
namespace Microsoft.Azure.Management.Sql.Fluent
{
    using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
    using Microsoft.Azure.Management.Sql.Fluent.Models;
    using System;

    /// <summary>
    /// An immutable client-side representation of an Azure SQL ElasticPool's Database Activity.
    /// </summary>
    public interface IElasticPoolDatabaseActivityBeta  :
        Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta
    {
        /// <summary>
        /// Gets the geo-location where the resource lives.
        /// </summary>
        string Location { get; }
    }
}


text:
package org.nustaq.kson;

import org.nustaq.serialization.FSTConfiguration;

import java.io.ObjectOutput;

/**
 * Created by ruedi on 12.08.2014.
 */
public class JSonSerializer extends KsonSerializer {

    protected String clazzAttributeName = "_type";
    protected boolean quoteKeyNames = true;
    private boolean tagTypes = true;

    public JSonSerializer(KsonCharOutput out, KsonTypeMapper mapper, FSTConfiguration conf) {
        super(out, mapper, conf);
    }

    public boolean isQuoteKeyNames() {
        return quoteKeyNames;
    }

    public void setQuoteKeyNames(boolean quoteKeyNames) {
        this.quoteKeyNames = quoteKeyNames;
    }

    public String getClazzAttributeName() {
        return clazzAttributeName;
    }

    public void setClazzAttributeName(String clazzAttributeName) {
        this.clazzAttributeName = clazzAttributeName;
    }

    @Override
    protected boolean shouldQuote(String string) {
        return true;
    }

    @Override
    protected void removeLastListSep() {
        out.back(2);
        out.writeChar('\n'); // hack, anyway json spec will not change and easy to fix in cases
    }

    @Override
    protected void writeListEnd() {
        out.writeChar(']');
    }

    @Override
    protected void writeListStart() {
        out.writeString("[ ");
    }

    @Override
    protected void writeListSep() {
        if (out.lastChar() == '\n') {
            out.back(1);
            out.writeChar(',');
            out.writeChar('\n');
        } else {
            out.writeString(", ");
        }
    }

    @Override
    protected void writeClazzTag(Class expectedClass, Object o) {
        if (!tagTypes || expectedClass == o.getClass()) {
            out.writeString("{");
        } else {
            String stringForType = mapper.getStringForType(o.getClass());
            if (quoteKeyNames) {
                out.writeString("{ \"" + clazzAttributeName + "\": \"" + stringForType + "\" ,");
            } else {
                out.writeString("{ " + clazzAttributeName + ": \"" + stringForType + "\" ,");
            }
        }
    }

    @Override
    protected void writeKey(String name) {
        if (quoteKeyNames) {
            out.writeChar('\"');
            super.writeKey(name);
            out.writeChar('\"');
        } else
            super.writeKey(name);
    }

    public JSonSerializer noTypeTags() {
        tagTypes = false;
        return this;
    }
}


text:
package gmapsfx.javascript.object;

import gmapsfx.javascript.JavascriptArray;
import gmapsfx.javascript.JavascriptObject;

public class MarkerShape extends JavascriptObject {
	private JavascriptArray coords;
	private String type;

	public MarkerShape() {
		super(GMapObjectType.OBJECT);
	}

	public MarkerShape coords(JavascriptArray coords) {
		setProperty("coords", coords);
		this.coords = coords;
		return this;
	}

	public MarkerShape type(String type) {
		setProperty("type", type);
		this.type = type;
		return this;
	}
}


text: Files uploaded through the http resource are temporarily stored here


text:
FROM node:6-slim

ADD package.json /usr/src/app/package.json
ADD index.html /usr/src/app/index.html
ADD src /usr/src/app/src

WORKDIR /usr/src/app
CMD node .


text:
package lars

import "net/url"

type nodeType uint8

const (
	isRoot nodeType = iota + 1
	hasParams
	matchesAny
)

type methodChain struct {
	handlerName string
	chain       HandlersChain
}

type existingParams map[string]struct{}

type node struct {
	path      string
	indices   string
	children  []*node
	handler   *methodChain
	priority  uint32
	nType     nodeType
	wildChild bool
}

func (e existingParams) Check(param string, path string) {

	if _, ok := e[param]; ok {
		panic("Duplicate param name '" + param + "' detected for route '" + path + "'")
	}

	e[param] = struct{}{}
}

// increments priority of the given child and reorders if necessary
func (n *node) incrementChildPrio(pos int) int {

	n.children[pos].priority++
	prio := n.children[pos].priority

	// adjust position (move to front)
	newPos := pos
	for newPos > 0 && n.children[newPos-1].priority < prio {
		// swap node positions
		tmpN := n.children[newPos-1]
		n.children[newPos-1] = n.children[newPos]
		n.children[newPos] = tmpN

		newPos--
	}

	// build new index char string
	if newPos != pos {
		n.indices = n.indices[:newPos] + // unchanged prefix, might be empty
			n.indices[pos:pos+1] + // the index char we move
			n.indices[newPos:pos] + n.indices[pos+1:] // rest without char at 'pos'
	}

	return newPos
}

// addRoute adds a node with the given handle to the path.
// here we set a Middleware because we have  to transfer all route's middlewares (it's a chain of functions) (with it's handler) to the node
func (n *node) add(path string, handlerName string, handler HandlersChain) (lp uint8) {

	var err error

	if path == blank {
		path = basePath
	}

	existing := make(existingParams)
	fullPath := path

	if path, err = url.QueryUnescape(path); err != nil {
		panic("Query Unescape Error on path '" + fullPath + "': " + err.Error())
	}

	fullPath = path

	n.priority++
	numParams := countParams(path)
	lp = numParams

	// non-empty tree
	if len(n.path) > 0 || len(n.children) > 0 {
	walk:
		for {
			// Find the longest common prefix.
			// This also implies that the common prefix contains no : or *
			// since the existing key can't contain those chars.
			i := 0
			max := min(len(path), len(n.path))
			for i < max && path[i] == n.path[i] {
				i++
			}

			// Split edge
			if i < len(n.path) {
				child := node{
					path:      n.path[i:],
					wildChild: n.wildChild,
					indices:   n.indices,
					children:  n.children,
					handler:   n.handler,
					priority:  n.priority - 1,
				}

				n.children = []*node{&child}
				// []byte for proper unicode char conversion, see httprouter #65
				n.indices = string([]byte{n.path[i]})
				n.path = path[:i]
				n.handler = nil
				n.wildChild = false
			}

			// Make new node a child of this node
			if i < len(path) {
				path = path[i:]

				if n.wildChild {
					n = n.children[0]
					n.priority++
					numParams--

					existing.Check(n.path, fullPath)

					// Check if the wildcard matches
					if len(path) >= len(n.path) && n.path == path[:len(n.path)] {

						// check for longer wildcard, e.g. :name and :names
						if len(n.path) >= len(path) || path[len(n.path)] == slashByte {
							continue walk
						}
					}

					panic("path segment '" + path +
						"' conflicts with existing wildcard '" + n.path +
						"' in path '" + fullPath + "'")
				}

				c := path[0]

				// slash after param
				if n.nType == hasParams && c == slashByte && len(n.children) == 1 {
					n = n.children[0]
					n.priority++
					continue walk
				}

				// Check if a child with the next path byte exists
				for i := 0; i < len(n.indices); i++ {
					if c == n.indices[i] {
						i = n.incrementChildPrio(i)
						n = n.children[i]
						continue walk
					}
				}

				// Otherwise insert it
				if c != paramByte && c != wildByte {

					// []byte for proper unicode char conversion, see httprouter #65
					n.indices += string([]byte{c})
					child := &node{}
					n.children = append(n.children, child)
					n.incrementChildPrio(len(n.indices) - 1)
					n = child
				}
				n.insertChild(numParams, existing, path, fullPath, handlerName, handler)
				return

			} else if i == len(path) { // Make node a (in-path) leaf
				if n.handler != nil {
					panic("handlers are already registered for path '" + fullPath + "'")
				}
				n.handler = &methodChain{
					handlerName: handlerName,
					chain:       handler,
				}
			}
			return
		}
	} else { // Empty tree
		n.insertChild(numParams, existing, path, fullPath, handlerName, handler)
		n.nType = isRoot
	}

	return
}

func (n *node) insertChild(numParams uint8, existing existingParams, path string, fullPath string, handlerName string, handler HandlersChain) {

	var offset int // already handled bytes of the path

	// find prefix until first wildcard (beginning with paramByte' or wildByte')
	for i, max := 0, len(path); numParams > 0; i++ {

		c := path[i]
		if c != paramByte && c != wildByte {
			continue
		}

		// find wildcard end (either '/' or path end)
		end := i + 1
		for end < max && path[end] != slashByte {
			switch path[end] {
			// the wildcard name must not contain ':' and '*'
			case paramByte, wildByte:
				panic("only one wildcard per path segment is allowed, has: '" +
					path[i:] + "' in path '" + fullPath + "'")
			default:
				end++
			}
		}

		// check if this Node existing children which would be
		// unreachable if we insert the wildcard here
		if len(n.children) > 0 {
			panic("wildcard route '" + path[i:end] +
				"' conflicts with existing children in path '" + fullPath + "'")
		}

		if c == paramByte { // param

			// check if the wildcard has a name
			if end-i < 2 {
				panic("wildcards must be named with a non-empty name in path '" + fullPath + "'")
			}

			// split path at the beginning of the wildcard
			if i > 0 {
				n.path = path[offset:i]
				offset = i
			}

			child := &node{
				nType: hasParams,
			}
			n.children = []*node{child}
			n.wildChild = true
			n = child
			n.priority++
			numParams--

			// if the path doesn't end with the wildcard, then there
			// will be another non-wildcard subpath starting with '/'
			if end < max {

				existing.Check(path[offset:end], fullPath)

				n.path = path[offset:end]
				offset = end

				child := &node{
					priority: 1,
				}
				n.children = []*node{child}
				n = child
			}

		} else { // catchAll
			if end != max || numParams > 1 {
				panic("Character after the * symbol is not permitted, path '" + fullPath + "'")
			}

			if len(n.path) > 0 && n.path[len(n.path)-1] == '/' {
				panic("catch-all conflicts with existing handle for the path segment root in path '" + fullPath + "'")
			}

			// currently fixed width 1 for '/'
			i--
			if path[i] != slashByte {
				panic("no / before catch-all in path '" + fullPath + "'")
			}

			n.path = path[offset:i]

			// first node: catchAll node with empty path
			child := &node{
				wildChild: true,
				nType:     matchesAny,
			}
			n.children = []*node{child}
			n.indices = string(path[i])
			n = child
			n.priority++

			// second node: node holding the variable
			child = &node{
				path:     path[i:],
				nType:    matchesAny,
				handler:  &methodChain{handlerName: handlerName, chain: handler},
				priority: 1,
			}
			n.children = []*node{child}

			return
		}
	}

	if n.nType == hasParams {
		existing.Check(path[offset:], fullPath)
	}

	// insert remaining path part and handle to the leaf
	n.path = path[offset:]
	n.handler = &methodChain{handlerName: handlerName, chain: handler}
}

// Returns the handle registered with the given path (key).
func (n *node) find(path string, po Params) (handler HandlersChain, p Params, handlerName string) {

	p = po

walk: // Outer loop for walking the tree
	for {
		if len(path) > len(n.path) {

			if path[:len(n.path)] == n.path {
				path = path[len(n.path):]

				// If this node does not have a wildcard (param or catchAll)
				// child,  we can just look up the next child node and continue
				// to walk down the tree
				if !n.wildChild {
					c := path[0]
					for i := 0; i < len(n.indices); i++ {
						if c == n.indices[i] {
							n = n.children[i]
							continue walk
						}
					}

					return
				}

				// handle wildcard child
				n = n.children[0]
				switch n.nType {
				case hasParams:

					// find param end (either '/' or path end)
					end := 0
					for end < len(path) && path[end] != slashByte {
						end++
					}

					// save param value
					i := len(p)
					p = p[:i+1] // expand slice within preallocated capacity
					p[i].Key = n.path[1:]
					p[i].Value = path[:end]

					// we need to go deeper!
					if end < len(path) {
						if len(n.children) > 0 {
							path = path[end:]
							n = n.children[0]
							continue walk
						}

						return
					}

					if n.handler != nil {
						handler = n.handler.chain
						handlerName = n.handler.handlerName
						return
					} else if len(n.children) == 1 {
						// No handle found. Check if a handle for this path
						n = n.children[0]
					}

					return

				case matchesAny:

					// save param value
					i := len(p)
					p = p[:i+1] // expand slice within preallocated capacity
					p[i].Key = WildcardParam
					p[i].Value = path[1:]

					handler = n.handler.chain
					handlerName = n.handler.handlerName
					return

					// can't happen, but left here in case I'm wrong
					// default:
					// 	panic("invalid node type")
				}
			}

		} else if path == n.path {

			// We should have reached the node containing the handle.
			// Check if this node has a handle registered.
			if n.handler != nil {
				if handler, handlerName = n.handler.chain, n.handler.handlerName; handler != nil {
					return
				}
			}
		}

		// Nothing found
		return
	}
}


text:
#ifndef IPA_PARAM_MANIPULATION_H
#define IPA_PARAM_MANIPULATION_H

/* Operation to be performed for the parameter in ipa_parm_adjustment
   below.  */
enum ipa_parm_op {
  IPA_PARM_OP_NONE,

  /* This describes a brand new parameter.

     The field `type' should be set to the new type, `arg_prefix'
     should be set to the string prefix for the new DECL_NAME, and
     `new_decl' will ultimately hold the newly created argument.  */
  IPA_PARM_OP_NEW,

  /* This new parameter is an unmodified parameter at index base_index. */
  IPA_PARM_OP_COPY,

  /* This adjustment describes a parameter that is about to be removed
     completely.  Most users will probably need to book keep those so that they
     don't leave behinfd any non default def ssa names belonging to them.  */
  IPA_PARM_OP_REMOVE
};

/* Structure to describe transformations of formal parameters and actual
   arguments.  Each instance describes one new parameter and they are meant to
   be stored in a vector.  Additionally, most users will probably want to store
   adjustments about parameters that are being removed altogether so that SSA
   names belonging to them can be replaced by SSA names of an artificial
   variable.  */
struct ipa_parm_adjustment
{
  /* The original PARM_DECL itself, helpful for processing of the body of the
     function itself.  Intended for traversing function bodies.
     ipa_modify_formal_parameters, ipa_modify_call_arguments and
     ipa_combine_adjustments ignore this and use base_index.
     ipa_modify_formal_parameters actually sets this.  */
  tree base;

  /* Type of the new parameter.  However, if by_ref is true, the real type will
     be a pointer to this type.  */
  tree type;

  /* Alias refrerence type to be used in MEM_REFs when adjusting caller
     arguments.  */
  tree alias_ptr_type;

  /* The new declaration when creating/replacing a parameter.  Created
     by ipa_modify_formal_parameters, useful for functions modifying
     the body accordingly.  For brand new arguments, this is the newly
     created argument.  */
  tree new_decl;

  /* New declaration of a substitute variable that we may use to replace all
     non-default-def ssa names when a parm decl is going away.  */
  tree new_ssa_base;

  /* If non-NULL and the original parameter is to be removed (copy_param below
     is NULL), this is going to be its nonlocalized vars value.  */
  tree nonlocal_value;

  /* This holds the prefix to be used for the new DECL_NAME.  */
  const char *arg_prefix;

  /* Offset into the original parameter (for the cases when the new parameter
     is a component of an original one).  */
  poly_int64_pod offset;

  /* Zero based index of the original parameter this one is based on.  */
  int base_index;

  /* Whether this parameter is a new parameter, a copy of an old one,
     or one about to be removed.  */
  enum ipa_parm_op op;

  /* Storage order of the original parameter (for the cases when the new
     parameter is a component of an original one).  */
  unsigned reverse : 1;

  /* The parameter is to be passed by reference.  */
  unsigned by_ref : 1;
};

typedef vec<ipa_parm_adjustment> ipa_parm_adjustment_vec;

vec<tree> ipa_get_vector_of_formal_parms (tree fndecl);
vec<tree> ipa_get_vector_of_formal_parm_types (tree fntype);
void ipa_modify_formal_parameters (tree fndecl, ipa_parm_adjustment_vec);
void ipa_modify_call_arguments (struct cgraph_edge *, gcall *,
				ipa_parm_adjustment_vec);
ipa_parm_adjustment_vec ipa_combine_adjustments (ipa_parm_adjustment_vec,
						 ipa_parm_adjustment_vec);
void ipa_dump_param_adjustments (FILE *, ipa_parm_adjustment_vec, tree);

bool ipa_modify_expr (tree *, bool, ipa_parm_adjustment_vec);
ipa_parm_adjustment *ipa_get_adjustment_candidate (tree **, bool *,
						   ipa_parm_adjustment_vec,
						   bool);

#endif	/* IPA_PARAM_MANIPULATION_H */


text:
package org.innovateuk.ifs.application.forms.sections.procurement.milestones.populator;

import org.innovateuk.ifs.application.forms.sections.procurement.milestones.form.ProcurementMilestoneForm;
import org.innovateuk.ifs.application.forms.sections.procurement.milestones.form.ProcurementMilestonesForm;
import org.innovateuk.ifs.procurement.milestone.resource.ProcurementMilestoneResource;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.IntStream;

@Component
public class ProcurementMilestoneFormPopulator {

    public <R extends ProcurementMilestoneResource> ProcurementMilestonesForm populate(List<R> resources) {
        Map<String, ProcurementMilestoneForm> map = new LinkedHashMap<>();

        IntStream
                .range(0, resources.size())
                .forEach(index -> map.put(
                        String.valueOf(resources.get(index).getId()),
                        new ProcurementMilestoneForm(resources.get(index), index)
            ));
        return new ProcurementMilestonesForm(map);
    }

}


text:
<?php
namespace PPI\Test\Form;

use PPI\Form\Element\Submit;

class SubmitTest extends \PHPUnit_Framework_TestCase
{

    protected $form;

    function setUp()
    {
        $this->form = new \PPI\Form\Form();
    }

    function tearDown()
    {
        unset($this->form);
    }

    function testCreate()
    {
        $output = $this->form->submit('Register')->render();
        $this->assertEquals($output, '<input type="submit" value="Register">');
    }

    function testCreateWithAttrs()
    {
        $output = $this->form->submit('Register', array('name' => 'foo', 'id' => 'bar'))->render();
        $this->assertEquals($output, '<input type="submit" value="Register" name="foo" id="bar">');
    }

    function testDirectClass()
    {
        $submit = new Submit(array(
            'value' => 'Register',
            'name' => 'foo',
            'id' => 'bar'
        ));
        $output = $submit->render();
        $this->assertEquals($output, '<input type="submit" value="Register" name="foo" id="bar">');
    }

    function testDirectClass__toString()
    {
        $submit = new Submit(array(
            'value' => 'Register',
            'name' => 'foo',
            'id' => 'bar'
        ));
        $output = (string)$submit;
        $this->assertEquals($output, '<input type="submit" value="Register" name="foo" id="bar">');
    }

    function testHasAttr()
    {
        $submit = new Submit(array(
            'value' => 'Register',
            'name' => 'foo',
            'id' => 'bar'
        ));
        $this->assertTrue($submit->hasAttr('name'));
        $this->assertFalse($submit->hasAttr('nonexistantattr'));
    }

    function testGetAttr()
    {
        $submit = new Submit(array(
            'value' => 'Register',
            'name' => 'foo',
            'id' => 'bar'
        ));
        $this->assertEquals('Register', $submit->attr('value'));
    }

    function testSetAttr()
    {
        $submit = new Submit(array(
            'value' => 'Register',
            'name' => 'foo',
            'id' => 'bar'
        ));
        $submit->attr('foo', 'bar');
        $this->assertEquals('bar', $submit->attr('foo'));
    }

    function testGetValues()
    {
        $submit = new Submit(array(
            'value' => 'submitvalue'
        ));
        $this->assertEquals('submitvalue', $submit->getValue());
        $this->assertEquals('submitvalue', $submit->attr('value'));
    }

    function testSetValue()
    {
        $submit = new Submit();
        $submit->setValue('submitvalue');
        $this->assertEquals('submitvalue', $submit->getValue());
    }
    /*
        function testGetSetRule() {

            $field = new Submit();

            $field->setRule('required');
            $this->assertTrue(count($field->getRule('required')) > 0);

            $field->setRule('maxlength', 32);
            $rule = $field->getRule('maxlength');
            $this->assertEquals($rule['value'], 32);
            $this->assertEquals($rule['type'], 'maxlength');
        }
    */
}


text:
// Copyright (c) 2014, Body Labs, Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
// OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
// AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
// WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

using Smithers.Reading.Calibration;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Smithers.Serialization.Writers
{
    public class CalibrationWriter : IWriter
    {
        CalibrationRecord _calibrationRecord;

        public CalibrationWriter(CalibrationRecord calibrationRecord)
        {
            _calibrationRecord = calibrationRecord;
        }

        public SavedItemType Type { get { return SavedItemType.CALIBRATION; } }

        public string FileExtension { get { return ".txt"; } }

        public TimeSpan? Timestamp { get { return null; } }

        public void Write(Stream stream)
        {
            _calibrationRecord.Write(stream);
        }
    }
}


text:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-hello',
  templateUrl: './hello.component.html',
  styleUrls: ['./hello.component.css']
})
export class HelloComponent implements OnInit {
  title = 'Hello Component.';
  constructor() {

  }

  ngOnInit() {

  }

}


text:
import {
    readJson,
    remove
} from 'fs-extra';
import webpack from 'webpack';
import WEBPACK_CONFIG from './fixtures/webpack.config';
import StatsWriterWebpackPlugin from '../src/index';

describe('StatsWriterWebpackPlugin', () => {
    const TMP_DIR = './test/fixtures/tmp',
        STATS_FILENAME = 'stats.json';

    function buildConfig(filename, options = {}) {
        const config = Object.assign({}, WEBPACK_CONFIG, options);

        config.plugins.push(new StatsWriterWebpackPlugin(filename));

        return config;
    }

    function compileConfig(options = {}, callback) {
        const compiler = webpack(options);

        if (options.watchOptions) {
            compiler.watch(options.watchOptions, callback);
        } else {
            compiler.run(callback);
        }
    }

    function compileAndCheck(filename, options = {}, callback) {
        const config = buildConfig(filename, options);

        compileConfig(config, (err, stats) => {
            expect(err).toEqual(null);

            readJson(stats.compilation.assets[filename].existsAt, (innerErr, json) => {
                expect(innerErr).toEqual(null);

                callback(json);
            });
        });
    }

    beforeEach(() => spyOn(console, 'log'));

    afterEach(done => remove(TMP_DIR, done));

    describe('#apply()', () => {
        describe('#run()', () => {
            it('should save stats successfully', done => compileAndCheck(STATS_FILENAME, {
                devtool: 'source-map'
            }, done));

            it('should add missing timings', done => {
                compileAndCheck(STATS_FILENAME, {
                    devtool: 'source-map'
                }, stats => {
                    expect(stats.time).not.toBeUndefined();

                    done();
                });
            });
        });

        describe('#watch()', () => {
            it('should save stats successfully', done => compileAndCheck(STATS_FILENAME, {
                devtool: 'source-map',
                watchOptions: {}
            }, done));
        });
    });
});


text:
<?php namespace BookStack\Services;

use Illuminate\Contracts\Filesystem\Factory as FileSystem;
use Illuminate\Contracts\Filesystem\Filesystem as FileSystemInstance;

class UploadService
{

    /**
     * @var FileSystem
     */
    protected $fileSystem;

    /**
     * @var FileSystemInstance
     */
    protected $storageInstance;

    /**
     * FileService constructor.
     * @param $fileSystem
     */
    public function __construct(FileSystem $fileSystem)
    {
        $this->fileSystem = $fileSystem;
    }

    /**
     * Get the storage that will be used for storing images.
     * @return FileSystemInstance
     */
    protected function getStorage()
    {
        if ($this->storageInstance !== null) return $this->storageInstance;

        $storageType = config('filesystems.default');
        $this->storageInstance = $this->fileSystem->disk($storageType);

        return $this->storageInstance;
    }

    /**
     * Check whether or not a folder is empty.
     * @param $path
     * @return bool
     */
    protected function isFolderEmpty($path)
    {
        $files = $this->getStorage()->files($path);
        $folders = $this->getStorage()->directories($path);
        return (count($files) === 0 && count($folders) === 0);
    }

    /**
     * Check if using a local filesystem.
     * @return bool
     */
    protected function isLocal()
    {
        return strtolower(config('filesystems.default')) === 'local';
    }
}


text:
```html
<amp-embed
  width="100"
  height="100"
  type="whopainfeed"
  layout="responsive"
  heights="(min-width:1907px) 39%, (min-width:1200px) 46%, (min-width:780px) 64%, (min-width:480px) 98%, (min-width:460px) 167%, 196%"
  data-siteId="1234"
  data-template="default"
>
</amp-embed>
```

## Configuration

For details on the configuration, please contact Whopa Team support@whopa.net \
These configurations are relevant for both `<amp-ad />` and `<amp-embed />`.

### Required parameters

-   `data-siteId`: Site ID provided by Whopa InFeed Team.

### Optional parameters

-   `data-template`: The Template of Widget.

**Resolution**

You can set an initial height of what the widget height is supposed to be. That is, instead of `height="100"`, if the widget's final height is 600px, then set `height="600"`. Setting the initial height **_will not_** finalize the widget height if it's different from the actual. The widget will resize to it's true dimensions after the widget leaves the viewport.


text:
import {ProjectorEventContext} from './projectorEventContext.js';
import {CameraType, LabelRenderParams, RenderContext} from './renderContext.js';
import {BoundingBox, ScatterPlotRectangleSelector} from './scatterPlotRectangleSelector.js';
import {ScatterPlotVisualizer} from './scatterPlotVisualizer.js';
import * as util from './util.js';
import {Point2D, Point3D} from './vector.js';

const BACKGROUND_COLOR = 0xffffff;

/**
 * The length of the cube (diameter of the circumscribing sphere) where all the
 * points live.
 */
const CUBE_LENGTH = 2;
const MAX_ZOOM = 5 * CUBE_LENGTH;
const MIN_ZOOM = 0.025 * CUBE_LENGTH;

// Constants relating to the camera parameters.
const PERSP_CAMERA_FOV_VERTICAL = 70;
const PERSP_CAMERA_NEAR_CLIP_PLANE = 0.01;
const PERSP_CAMERA_FAR_CLIP_PLANE = 100;
const ORTHO_CAMERA_FRUSTUM_HALF_EXTENT = 1.2;

// Key presses.
const SHIFT_KEY = 16;
const CTRL_KEY = 17;

const START_CAMERA_POS_3D = new THREE.Vector3(0.45, 0.9, 1.6);
const START_CAMERA_TARGET_3D = new THREE.Vector3(0, 0, 0);
const START_CAMERA_POS_2D = new THREE.Vector3(0, 0, 4);
const START_CAMERA_TARGET_2D = new THREE.Vector3(0, 0, 0);

const ORBIT_MOUSE_ROTATION_SPEED = 1;
const ORBIT_ANIMATION_ROTATION_CYCLE_IN_SECONDS = 7;

export type OnCameraMoveListener =
    (cameraPosition: THREE.Vector3, cameraTarget: THREE.Vector3) => void;

/** Supported modes of interaction. */
export enum MouseMode {
  AREA_SELECT,
  CAMERA_AND_CLICK_SELECT
}

/** Defines a camera, suitable for serialization. */
export class CameraDef {
  orthographic: boolean = false;
  position: Point3D;
  target: Point3D;
  zoom: number;
}

/**
 * Maintains a three.js instantiation and context,
 * animation state, and all other logic that's
 * independent of how a 3D scatter plot is actually rendered. Also holds an
 * array of visualizers and dispatches application events to them.
 */
export class ScatterPlot {
  private visualizers: ScatterPlotVisualizer[] = [];

  private onCameraMoveListeners: OnCameraMoveListener[] = [];

  private height: number;
  private width: number;

  private mouseMode: MouseMode;
  private backgroundColor: number = BACKGROUND_COLOR;

  private dimensionality: number = 3;
  private renderer: THREE.WebGLRenderer;

  private scene: THREE.Scene;
  private pickingTexture: THREE.WebGLRenderTarget;
  private light: THREE.PointLight;

  private cameraDef: CameraDef = null;
  private camera: THREE.Camera;
  private orbitAnimationOnNextCameraCreation: boolean = false;
  private orbitCameraControls: any;
  private orbitAnimationId: number;

  private worldSpacePointPositions: Float32Array;
  private pointColors: Float32Array;
  private pointScaleFactors: Float32Array;
  private labels: LabelRenderParams;
  private polylineColors: {[polylineIndex: number]: Float32Array};
  private polylineOpacities: Float32Array;
  private polylineWidths: Float32Array;

  private selecting = false;
  private nearestPoint: number;
  private mouseIsDown = false;
  private isDragSequence = false;
  private rectangleSelector: ScatterPlotRectangleSelector;

  constructor(
      private container: HTMLElement,
      private projectorEventContext: ProjectorEventContext) {
    this.getLayoutValues();

    this.scene = new THREE.Scene();
    this.renderer = new THREE.WebGLRenderer(
        {alpha: true, premultipliedAlpha: false, antialias: false});
    this.renderer.setClearColor(BACKGROUND_COLOR, 1);
    this.container.appendChild(this.renderer.domElement);
    this.light = new THREE.PointLight(0xFFECBF, 1, 0);
    this.scene.add(this.light);

    this.setDimensions(3);
    this.recreateCamera(this.makeDefaultCameraDef(this.dimensionality));
    this.renderer.render(this.scene, this.camera);

    this.rectangleSelector = new ScatterPlotRectangleSelector(
        this.container,
        (boundingBox: BoundingBox) => this.selectBoundingBox(boundingBox));
    this.addInteractionListeners();
  }

  private addInteractionListeners() {
    this.container.addEventListener('mousemove', this.onMouseMove.bind(this));
    this.container.addEventListener('mousedown', this.onMouseDown.bind(this));
    this.container.addEventListener('mouseup', this.onMouseUp.bind(this));
    this.container.addEventListener('click', this.onClick.bind(this));
    window.addEventListener('keydown', this.onKeyDown.bind(this), false);
    window.addEventListener('keyup', this.onKeyUp.bind(this), false);
  }

  private addCameraControlsEventListeners(cameraControls: any) {
    // Start is called when the user stars interacting with
    // controls.
    cameraControls.addEventListener('start', () => {
      this.stopOrbitAnimation();
      this.onCameraMoveListeners.forEach(
          l => l(this.camera.position, cameraControls.target));
    });

    // Change is called everytime the user interacts with the controls.
    cameraControls.addEventListener('change', () => {
      this.render();
    });

    // End is called when the user stops interacting with the
    // controls (e.g. on mouse up, after dragging).
    cameraControls.addEventListener('end', () => {});
  }

  private makeOrbitControls(
      camera: THREE.Camera, cameraDef: CameraDef, cameraIs3D: boolean) {
    if (this.orbitCameraControls != null) {
      this.orbitCameraControls.dispose();
    }
    const occ =
        new (THREE as any).OrbitControls(camera, this.renderer.domElement);
    occ.target0 = new THREE.Vector3(
        cameraDef.target[0], cameraDef.target[1], cameraDef.target[2]);
    occ.position0 = new THREE.Vector3().copy(camera.position);
    occ.zoom0 = cameraDef.zoom;
    occ.enableRotate = cameraIs3D;
    occ.autoRotate = false;
    occ.rotateSpeed = ORBIT_MOUSE_ROTATION_SPEED;
    if (cameraIs3D) {
      occ.mouseButtons.ORBIT = THREE.MOUSE.LEFT;
      occ.mouseButtons.PAN = THREE.MOUSE.RIGHT;
    } else {
      occ.mouseButtons.ORBIT = null;
      occ.mouseButtons.PAN = THREE.MOUSE.LEFT;
    }
    occ.reset();

    this.camera = camera;
    this.orbitCameraControls = occ;
    this.addCameraControlsEventListeners(this.orbitCameraControls);
  }

  private makeCamera3D(cameraDef: CameraDef, w: number, h: number) {
    let camera: THREE.PerspectiveCamera;
    {
      const aspectRatio = w / h;
      camera = new THREE.PerspectiveCamera(
          PERSP_CAMERA_FOV_VERTICAL, aspectRatio, PERSP_CAMERA_NEAR_CLIP_PLANE,
          PERSP_CAMERA_FAR_CLIP_PLANE);
      camera.position.set(
          cameraDef.position[0], cameraDef.position[1], cameraDef.position[2]);
      const at = new THREE.Vector3(
          cameraDef.target[0], cameraDef.target[1], cameraDef.target[2]);
      camera.lookAt(at);
      camera.zoom = cameraDef.zoom;
      camera.updateProjectionMatrix();
    }
    this.camera = camera;
    this.makeOrbitControls(camera, cameraDef, true);
  }

  private makeCamera2D(cameraDef: CameraDef, w: number, h: number) {
    let camera: THREE.OrthographicCamera;
    const target = new THREE.Vector3(
        cameraDef.target[0], cameraDef.target[1], cameraDef.target[2]);
    {
      const aspectRatio = w / h;
      let left = -ORTHO_CAMERA_FRUSTUM_HALF_EXTENT;
      let right = ORTHO_CAMERA_FRUSTUM_HALF_EXTENT;
      let bottom = -ORTHO_CAMERA_FRUSTUM_HALF_EXTENT;
      let top = ORTHO_CAMERA_FRUSTUM_HALF_EXTENT;
      // Scale up the larger of (w, h) to match the aspect ratio.
      if (aspectRatio > 1) {
        left *= aspectRatio;
        right *= aspectRatio;
      } else {
        top /= aspectRatio;
        bottom /= aspectRatio;
      }
      camera =
          new THREE.OrthographicCamera(left, right, top, bottom, -1000, 1000);
      camera.position.set(
          cameraDef.position[0], cameraDef.position[1], cameraDef.position[2]);
      camera.up = new THREE.Vector3(0, 1, 0);
      camera.lookAt(target);
      camera.zoom = cameraDef.zoom;
      camera.updateProjectionMatrix();
    }
    this.camera = camera;
    this.makeOrbitControls(camera, cameraDef, false);
  }

  private makeDefaultCameraDef(dimensionality: number): CameraDef {
    const def = new CameraDef();
    def.orthographic = (dimensionality === 2);
    def.zoom = 1.0;
    if (def.orthographic) {
      def.position =
          [START_CAMERA_POS_2D.x, START_CAMERA_POS_2D.y, START_CAMERA_POS_2D.z];
      def.target = [
        START_CAMERA_TARGET_2D.x, START_CAMERA_TARGET_2D.y,
        START_CAMERA_TARGET_2D.z
      ];
    } else {
      def.position =
          [START_CAMERA_POS_3D.x, START_CAMERA_POS_3D.y, START_CAMERA_POS_3D.z];
      def.target = [
        START_CAMERA_TARGET_3D.x, START_CAMERA_TARGET_3D.y,
        START_CAMERA_TARGET_3D.z
      ];
    }
    return def;
  }

  /** Recreate the scatter plot camera from a definition structure. */
  recreateCamera(cameraDef: CameraDef) {
    if (cameraDef.orthographic) {
      this.makeCamera2D(cameraDef, this.width, this.height);
    } else {
      this.makeCamera3D(cameraDef, this.width, this.height);
    }
    this.orbitCameraControls.minDistance = MIN_ZOOM;
    this.orbitCameraControls.maxDistance = MAX_ZOOM;
    this.orbitCameraControls.update();
    if (this.orbitAnimationOnNextCameraCreation) {
      this.startOrbitAnimation();
    }
  }

  private onClick(e?: MouseEvent, notify = true) {
    if (e && this.selecting) {
      return;
    }
    // Only call event handlers if the click originated from the scatter plot.
    if (!this.isDragSequence && notify) {
      const selection = (this.nearestPoint != null) ? [this.nearestPoint] : [];
      this.projectorEventContext.notifySelectionChanged(selection);
    }
    this.isDragSequence = false;
    this.render();
  }

  private onMouseDown(e: MouseEvent) {
    this.isDragSequence = false;
    this.mouseIsDown = true;
    if (this.selecting) {
      this.orbitCameraControls.enabled = false;
      this.rectangleSelector.onMouseDown(e.offsetX, e.offsetY);
      this.setNearestPointToMouse(e);
    } else if (
        !e.ctrlKey && this.sceneIs3D() &&
        this.orbitCameraControls.mouseButtons.ORBIT === THREE.MOUSE.RIGHT) {
      // The user happened to press the ctrl key when the tab was active,
      // unpressed the ctrl when the tab was inactive, and now he/she
      // is back to the projector tab.
      this.orbitCameraControls.mouseButtons.ORBIT = THREE.MOUSE.LEFT;
      this.orbitCameraControls.mouseButtons.PAN = THREE.MOUSE.RIGHT;
    } else if (
        e.ctrlKey && this.sceneIs3D() &&
        this.orbitCameraControls.mouseButtons.ORBIT === THREE.MOUSE.LEFT) {
      // Similarly to the situation above.
      this.orbitCameraControls.mouseButtons.ORBIT = THREE.MOUSE.RIGHT;
      this.orbitCameraControls.mouseButtons.PAN = THREE.MOUSE.LEFT;
    }
  }

  /** When we stop dragging/zooming, return to normal behavior. */
  private onMouseUp(e: any) {
    if (this.selecting) {
      this.orbitCameraControls.enabled = true;
      this.rectangleSelector.onMouseUp();
      this.render();
    }
    this.mouseIsDown = false;
  }

  /**
   * When the mouse moves, find the nearest point (if any) and send it to the
   * hoverlisteners (usually called from embedding.ts)
   */
  private onMouseMove(e: MouseEvent) {
    this.isDragSequence = this.mouseIsDown;
    // Depending if we're selecting or just navigating, handle accordingly.
    if (this.selecting && this.mouseIsDown) {
      this.rectangleSelector.onMouseMove(e.offsetX, e.offsetY);
      this.render();
    } else if (!this.mouseIsDown) {
      this.setNearestPointToMouse(e);
      this.projectorEventContext.notifyHoverOverPoint(this.nearestPoint);
    }
  }

  /** For using ctrl + left click as right click, and for circle select */
  private onKeyDown(e: any) {
    // If ctrl is pressed, use left click to orbit
    if (e.keyCode === CTRL_KEY && this.sceneIs3D()) {
      this.orbitCameraControls.mouseButtons.ORBIT = THREE.MOUSE.RIGHT;
      this.orbitCameraControls.mouseButtons.PAN = THREE.MOUSE.LEFT;
    }

    // If shift is pressed, start selecting
    if (e.keyCode === SHIFT_KEY) {
      this.selecting = true;
      this.container.style.cursor = 'crosshair';
    }
  }

  /** For using ctrl + left click as right click, and for circle select */
  private onKeyUp(e: any) {
    if (e.keyCode === CTRL_KEY && this.sceneIs3D()) {
      this.orbitCameraControls.mouseButtons.ORBIT = THREE.MOUSE.LEFT;
      this.orbitCameraControls.mouseButtons.PAN = THREE.MOUSE.RIGHT;
    }

    // If shift is released, stop selecting
    if (e.keyCode === SHIFT_KEY) {
      this.selecting = (this.getMouseMode() === MouseMode.AREA_SELECT);
      if (!this.selecting) {
        this.container.style.cursor = 'default';
      }
      this.render();
    }
  }

  /**
   * Returns a list of indices of points in a bounding box from the picking
   * texture.
   * @param boundingBox The bounding box to select from.
   */
  private getPointIndicesFromPickingTexture(boundingBox: BoundingBox):
      number[] {
    if (this.worldSpacePointPositions == null) {
      return null;
    }
    const pointCount = this.worldSpacePointPositions.length / 3;
    const dpr = window.devicePixelRatio || 1;
    const x = Math.floor(boundingBox.x * dpr);
    const y = Math.floor(boundingBox.y * dpr);
    const width = Math.floor(boundingBox.width * dpr);
    const height = Math.floor(boundingBox.height * dpr);

    // Create buffer for reading all of the pixels from the texture.
    let pixelBuffer = new Uint8Array(width * height * 4);

    // Read the pixels from the bounding box.
    this.renderer.readRenderTargetPixels(
        this.pickingTexture, x, this.pickingTexture.height - y, width, height,
        pixelBuffer);

    // Keep a flat list of each point and whether they are selected or not. This
    // approach is more efficient than using an object keyed by the index.
    let pointIndicesSelection =
        new Uint8Array(this.worldSpacePointPositions.length);
    for (let i = 0; i < width * height; i++) {
      const id = (pixelBuffer[i * 4] << 16) | (pixelBuffer[i * 4 + 1] << 8) |
          pixelBuffer[i * 4 + 2];
      if (id !== 0xffffff && (id < pointCount)) {
        pointIndicesSelection[id] = 1;
      }
    }
    let pointIndices: number[] = [];
    for (let i = 0; i < pointIndicesSelection.length; i++) {
      if (pointIndicesSelection[i] === 1) {
        pointIndices.push(i);
      }
    }

    return pointIndices;
  }

  private selectBoundingBox(boundingBox: BoundingBox) {
    let pointIndices = this.getPointIndicesFromPickingTexture(boundingBox);
    this.projectorEventContext.notifySelectionChanged(pointIndices);
  }

  private setNearestPointToMouse(e: MouseEvent) {
    if (this.pickingTexture == null) {
      this.nearestPoint = null;
      return;
    }
    const boundingBox:
        BoundingBox = {x: e.offsetX, y: e.offsetY, width: 1, height: 1};
    const pointIndices = this.getPointIndicesFromPickingTexture(boundingBox);
    this.nearestPoint = (pointIndices != null) ? pointIndices[0] : null;
  }

  private getLayoutValues(): Point2D {
    this.width = this.container.offsetWidth;
    this.height = Math.max(1, this.container.offsetHeight);
    return [this.width, this.height];
  }

  private sceneIs3D(): boolean {
    return this.dimensionality === 3;
  }

  private remove3dAxisFromScene(): THREE.Object3D {
    const axes = this.scene.getObjectByName('axes');
    if (axes != null) {
      this.scene.remove(axes);
    }
    return axes;
  }

  private add3dAxis() {
    const axes = new THREE.AxisHelper();
    axes.name = 'axes';
    this.scene.add(axes);
  }

  /** Set 2d vs 3d mode. */
  setDimensions(dimensionality: number) {
    if ((dimensionality !== 2) && (dimensionality !== 3)) {
      throw new RangeError('dimensionality must be 2 or 3');
    }
    this.dimensionality = dimensionality;

    const def = this.cameraDef || this.makeDefaultCameraDef(dimensionality);
    this.recreateCamera(def);

    this.remove3dAxisFromScene();
    if (dimensionality === 3) {
      this.add3dAxis();
    }
  }

  /** Gets the current camera information, suitable for serialization. */
  getCameraDef(): CameraDef {
    const def = new CameraDef();
    const pos = this.camera.position;
    const tgt = this.orbitCameraControls.target;
    def.orthographic = !this.sceneIs3D();
    def.position = [pos.x, pos.y, pos.z];
    def.target = [tgt.x, tgt.y, tgt.z];
    def.zoom = (this.camera as any).zoom;
    return def;
  }

  /** Sets parameters for the next camera recreation. */
  setCameraParametersForNextCameraCreation(
      def: CameraDef, orbitAnimation: boolean) {
    this.cameraDef = def;
    this.orbitAnimationOnNextCameraCreation = orbitAnimation;
  }

  /** Gets the current camera position. */
  getCameraPosition(): Point3D {
    const currPos = this.camera.position;
    return [currPos.x, currPos.y, currPos.z];
  }

  /** Gets the current camera target. */
  getCameraTarget(): Point3D {
    let currTarget = this.orbitCameraControls.target;
    return [currTarget.x, currTarget.y, currTarget.z];
  }

  /** Sets up the camera from given position and target coordinates. */
  setCameraPositionAndTarget(position: Point3D, target: Point3D) {
    this.stopOrbitAnimation();
    this.camera.position.set(position[0], position[1], position[2]);
    this.orbitCameraControls.target.set(target[0], target[1], target[2]);
    this.orbitCameraControls.update();
    this.render();
  }

  /** Starts orbiting the camera around its current lookat target. */
  startOrbitAnimation() {
    if (!this.sceneIs3D()) {
      return;
    }
    if (this.orbitAnimationId != null) {
      this.stopOrbitAnimation();
    }
    this.orbitCameraControls.autoRotate = true;
    this.orbitCameraControls.rotateSpeed =
        ORBIT_ANIMATION_ROTATION_CYCLE_IN_SECONDS;
    this.updateOrbitAnimation();
  }

  private updateOrbitAnimation() {
    this.orbitCameraControls.update();
    this.orbitAnimationId =
        requestAnimationFrame(() => this.updateOrbitAnimation());
  }

  /** Stops the orbiting animation on the camera. */
  stopOrbitAnimation() {
    this.orbitCameraControls.autoRotate = false;
    this.orbitCameraControls.rotateSpeed = ORBIT_MOUSE_ROTATION_SPEED;
    if (this.orbitAnimationId != null) {
      cancelAnimationFrame(this.orbitAnimationId);
      this.orbitAnimationId = null;
    }
  }

  /** Adds a visualizer to the set, will start dispatching events to it */
  addVisualizer(visualizer: ScatterPlotVisualizer) {
    if (this.scene) {
      visualizer.setScene(this.scene);
    }
    visualizer.onResize(this.width, this.height);
    visualizer.onPointPositionsChanged(this.worldSpacePointPositions);
    this.visualizers.push(visualizer);
  }

  /** Removes all visualizers attached to this scatter plot. */
  removeAllVisualizers() {
    this.visualizers.forEach(v => v.dispose());
    this.visualizers = [];
  }

  /** Update scatter plot with a new array of packed xyz point positions. */
  setPointPositions(worldSpacePointPositions: Float32Array) {
    this.worldSpacePointPositions = worldSpacePointPositions;
    this.visualizers.forEach(
        v => v.onPointPositionsChanged(worldSpacePointPositions));
  }

  render() {
    {
      const lightPos = this.camera.position.clone();
      lightPos.x += 1;
      lightPos.y += 1;
      this.light.position.set(lightPos.x, lightPos.y, lightPos.z);
    }

    const cameraType = (this.camera instanceof THREE.PerspectiveCamera) ?
        CameraType.Perspective :
        CameraType.Orthographic;

    let cameraSpacePointExtents: [number, number] = [0, 0];
    if (this.worldSpacePointPositions != null) {
      cameraSpacePointExtents = util.getNearFarPoints(
          this.worldSpacePointPositions, this.camera.position,
          this.orbitCameraControls.target);
    }

    const rc = new RenderContext(
        this.camera, cameraType, this.orbitCameraControls.target, this.width,
        this.height, cameraSpacePointExtents[0], cameraSpacePointExtents[1],
        this.backgroundColor, this.pointColors, this.pointScaleFactors,
        this.labels, this.polylineColors, this.polylineOpacities,
        this.polylineWidths);

    // Render first pass to picking target. This render fills pickingTexture
    // with colors that are actually point ids, so that sampling the texture at
    // the mouse's current x,y coordinates will reveal the data point that the
    // mouse is over.
    this.visualizers.forEach(v => v.onPickingRender(rc));

    {
      const axes = this.remove3dAxisFromScene();
      this.renderer.render(this.scene, this.camera, this.pickingTexture);
      if (axes != null) {
        this.scene.add(axes);
      }
    }

    // Render second pass to color buffer, to be displayed on the canvas.
    this.visualizers.forEach(v => v.onRender(rc));

    this.renderer.render(this.scene, this.camera);
  }

  setMouseMode(mouseMode: MouseMode) {
    this.mouseMode = mouseMode;
    if (mouseMode === MouseMode.AREA_SELECT) {
      this.selecting = true;
      this.container.style.cursor = 'crosshair';
    } else {
      this.selecting = false;
      this.container.style.cursor = 'default';
    }
  }

  /** Set the colors for every data point. (RGB triplets) */
  setPointColors(colors: Float32Array) {
    this.pointColors = colors;
  }

  /** Set the scale factors for every data point. (scalars) */
  setPointScaleFactors(scaleFactors: Float32Array) {
    this.pointScaleFactors = scaleFactors;
  }

  /** Set the labels to rendered */
  setLabels(labels: LabelRenderParams) {
    this.labels = labels;
  }

  /** Set the colors for every data polyline. (RGB triplets) */
  setPolylineColors(colors: {[polylineIndex: number]: Float32Array}) {
    this.polylineColors = colors;
  }

  setPolylineOpacities(opacities: Float32Array) {
    this.polylineOpacities = opacities;
  }

  setPolylineWidths(widths: Float32Array) {
    this.polylineWidths = widths;
  }

  getMouseMode(): MouseMode {
    return this.mouseMode;
  }

  resetZoom() {
    this.recreateCamera(this.makeDefaultCameraDef(this.dimensionality));
    this.render();
  }

  setDayNightMode(isNight: boolean) {
    const canvases = this.container.querySelectorAll('canvas');
    const filterValue = isNight ? 'invert(100%)' : null;
    for (let i = 0; i < canvases.length; i++) {
      canvases[i].style.filter = filterValue;
    }
  }

  resize(render = true) {
    const [oldW, oldH] = [this.width, this.height];
    const [newW, newH] = this.getLayoutValues();

    if (this.dimensionality === 3) {
      const camera = (this.camera as THREE.PerspectiveCamera);
      camera.aspect = newW / newH;
      camera.updateProjectionMatrix();
    } else {
      const camera = (this.camera as THREE.OrthographicCamera);
      // Scale the ortho frustum by however much the window changed.
      const scaleW = newW / oldW;
      const scaleH = newH / oldH;
      const newCamHalfWidth = ((camera.right - camera.left) * scaleW) / 2;
      const newCamHalfHeight = ((camera.top - camera.bottom) * scaleH) / 2;
      camera.top = newCamHalfHeight;
      camera.bottom = -newCamHalfHeight;
      camera.left = -newCamHalfWidth;
      camera.right = newCamHalfWidth;
      camera.updateProjectionMatrix();
    }

    // Accouting for retina displays.
    const dpr = window.devicePixelRatio || 1;
    this.renderer.setPixelRatio(dpr);
    this.renderer.setSize(newW, newH);

    // the picking texture needs to be exactly the same as the render texture.
    {
      const renderCanvasSize = this.renderer.getSize();
      const pixelRatio = this.renderer.getPixelRatio();
      this.pickingTexture = new THREE.WebGLRenderTarget(
          renderCanvasSize.width * pixelRatio,
          renderCanvasSize.height * pixelRatio);
      this.pickingTexture.texture.minFilter = THREE.LinearFilter;
    }

    this.visualizers.forEach(v => v.onResize(newW, newH));

    if (render) {
      this.render();
    };
  }

  onCameraMove(listener: OnCameraMoveListener) {
    this.onCameraMoveListeners.push(listener);
  }

  clickOnPoint(pointIndex: number) {
    this.nearestPoint = pointIndex;
    this.onClick(null, false);
  }
}


text:
LDA
===
Implementation of Linear Discriminant Analysis (LDA) algorithm which can be used for binary classification of multivariate data.
###Basic LDA (for 2 classes):
```python
>>> from LDA import LDA
>>> t = LDA([[2.4, 5.4, 3.3], [5, 6.6, 3.4], [2.1, 2.4, 2.5], [5, 3.1, 6]], ['A', 'A', 'B', 'B'])
>>> t.predict([2.3, 3.2, 2.4])
>>> {'A': 2.1366024891345905, 'B': 3.2231442139356759}
```
or pass `True` in `t.predict()` to get the classifier result:
```python
>>> t.predict([2.3, 3.2, 2.4], True)
>>> 'B'
```

Each of the binary classes above ('A' and 'B') are predicted based on the standard discriminant function i.e. ![alt text](https://github.com/saifuddin778/LDA/raw/master/images/lda.png ""), and one with maximum output is the predicted class for the given input.
###Multiclass LDA (Pairwise implementation):
If the dataset has more than two classes i.e. K > 2, then it can be processed with all the possible combinations of classes, which results in ```K(K-1)/2``` classifiers trained for each combination. Moreover, the classification decision is made by the popular desicion system as specified by [Wu et, al. (2004)](http://www.csie.ntu.edu.tw/~cjlin/papers/svmprob/svmprob.pdf):
```python
>>> from LDA import multiclass_LDA
>>> t = multiclass_LDA(labels, classes)
>>> t.predict(vector)
>>> 'predicted class'
```
or pass `False` in `t.predict()` to get scores from all the classifiers:
```python
>>> t.predict(vector, False)
>>> [{'A': score, 'B': score}, {'A': score, 'C': score}, {'C': score, 'A': score}]
```


text:
NTSTATUS PciGetConfigHandlers(__in PPCI_FDO_EXTENSION FdoExt)
{
	ASSERT(!FdoExt->BusHandler);

	NTSTATUS Status										= STATUS_SUCCESS;

	if(FdoExt->BusRootFdoExtension == FdoExt)
	{
		//
		// this is root bus fdo
		//
		ASSERT(!FdoExt->PciBusInterface);

		//
		// query pci bus interface
		//
		Status											= PciQueryForPciBusInterface(FdoExt);
		if(NT_SUCCESS(Status))
		{
			//
			// acpi gave us a pci bus interfer,use it
			//
			PciAssignBusNumbers							= TRUE;
			return Status;
		}

		//
		// we need to call hal to get a bus handler
		//
		ASSERT(!PciAssignBusNumbers);
	}
	else
	{
		//
		// root bus has already got a pci bus interfer,done
		//
		if(FdoExt->BusRootFdoExtension->PciBusInterface)
			return STATUS_SUCCESS;

		Status											= STATUS_NOT_SUPPORTED;
	}

	ASSERT(Status == STATUS_NOT_SUPPORTED);

	ASSERT(!PciAssignBusNumbers);

	FdoExt->BusHandler									= HalReferenceHandlerForBus(PCIBus,FdoExt->BaseBus);

	return FdoExt->BusHandler ? STATUS_SUCCESS : STATUS_UNSUCCESSFUL;
}

//
// query bus interface [checked]
//
NTSTATUS PciQueryForPciBusInterface(__in PPCI_FDO_EXTENSION FdoExt)
{
	PAGED_CODE();

	ASSERT(FdoExt->Common.ExtensionType == PciFdoExtensionType && FdoExt->BusRootFdoExtension == FdoExt);

	PPCI_BUS_INTERFACE_STANDARD Interface				= 0;
	PDEVICE_OBJECT DeviceObject							= 0;
	NTSTATUS Status										= STATUS_SUCCESS;

	__try
	{
		ULONG Length									= sizeof(PCI_BUS_INTERFACE_STANDARD);
		Interface										= static_cast<PPCI_BUS_INTERFACE_STANDARD>(ExAllocatePoolWithTag(NonPagedPool,Length,'BicP'));
		if(!Interface)
			try_leave(Status = STATUS_INSUFFICIENT_RESOURCES);

		DeviceObject									= IoGetAttachedDeviceReference(FdoExt->PhysicalDeviceObject);
		if(!DeviceObject)
			try_leave(Status = STATUS_NO_SUCH_DEVICE);

		KEVENT Event;
		KeInitializeEvent(&Event,SynchronizationEvent,FALSE);

		IO_STATUS_BLOCK IoStatus;
		PIRP Irp										= IoBuildSynchronousFsdRequest(IRP_MJ_PNP,DeviceObject,0,0,0,&Event,&IoStatus);
		if(!Irp)
			try_leave(Status = STATUS_INSUFFICIENT_RESOURCES);

		PIO_STACK_LOCATION IrpSp						= IoGetNextIrpStackLocation(Irp);
		IrpSp->MajorFunction							= IRP_MJ_PNP;
		IrpSp->MinorFunction							= IRP_MN_QUERY_INTERFACE;
		IrpSp->Parameters.QueryInterface.InterfaceType	= &GUID_PCI_BUS_INTERFACE_STANDARD;
		IrpSp->Parameters.QueryInterface.Interface		= reinterpret_cast<PINTERFACE>(Interface);
		IrpSp->Parameters.QueryInterface.Size			= static_cast<USHORT>(Length);
		IrpSp->Parameters.QueryInterface.Version		= PCI_BUS_INTERFACE_STANDARD_VERSION;
		IrpSp->Parameters.Others.Argument4				= 0;
		Irp->IoStatus.Status							= STATUS_NOT_SUPPORTED;
		Irp->IoStatus.Information						= 0;

		Status											= IoCallDriver(DeviceObject,Irp);
		if(Status == STATUS_PENDING)
		{
			KeWaitForSingleObject(&Event,Executive,KernelMode,FALSE,0);
			Status										= IoStatus.Status;
		}

		if(NT_SUCCESS(Status))
		{
			FdoExt->PciBusInterface						= Interface;
			Interface									= 0;
		}
	}
	__finally
	{
		if(Interface)
			ExFreePool(Interface);

		if(DeviceObject)
			ObDereferenceObject(DeviceObject);
	}

	return Status;
}

//
// read device config [checked]
//
ULONG PciReadDeviceConfig(__in PPCI_PDO_EXTENSION PdoExt,__in PVOID Buffer,__in ULONG Offset,__in ULONG Length)
{
	return PciReadWriteConfigSpace(PdoExt->ParentFdoExtension,PdoExt->Slot,Buffer,Offset,Length,TRUE);
}

//
// write device config [checked]
//
ULONG PciWriteDeviceConfig(__in PPCI_PDO_EXTENSION PdoExt,__in PVOID Buffer,__in ULONG Offset,__in ULONG Length)
{
	return PciReadWriteConfigSpace(PdoExt->ParentFdoExtension,PdoExt->Slot,Buffer,Offset,Length,FALSE);
}

//
// read slot config [checked]
//
ULONG PciReadSlotConfig(__in PPCI_FDO_EXTENSION FdoExt,__in PCI_SLOT_NUMBER Slot,__in PVOID Buffer,__in ULONG Offset,__in ULONG Length)
{
	return PciReadWriteConfigSpace(FdoExt,Slot,Buffer,Offset,Length,TRUE);
}

//
// write device config [checked]
//
ULONG PciWriteSlotConfig(__in PPCI_FDO_EXTENSION FdoExt,__in PCI_SLOT_NUMBER Slot,__in PVOID Buffer,__in ULONG Offset,__in ULONG Length)
{
	return PciReadWriteConfigSpace(FdoExt,Slot,Buffer,Offset,Length,FALSE);
}

//
// read write config space [checked]
//
ULONG PciReadWriteConfigSpace(__in PPCI_FDO_EXTENSION FdoExt,__in PCI_SLOT_NUMBER Slot,__in PVOID Buffer,__in ULONG Offset,__in ULONG Length,__in BOOLEAN Read)
{
	PPCI_FDO_EXTENSION RootFdoExt						= FdoExt->BusRootFdoExtension;
	ASSERT(RootFdoExt == RootFdoExt->BusRootFdoExtension);

	if(RootFdoExt->PciBusInterface)
	{
		ULONG ResultLength								= 0;
		PCI_READ_WRITE_CONFIG Function					= Read ? RootFdoExt->PciBusInterface->ReadConfig : RootFdoExt->PciBusInterface->WriteConfig;

		ResultLength									= Function(RootFdoExt->PciBusInterface->Context,FdoExt->BaseBus,Slot.u.AsULONG,Buffer,Offset,Length);
		if(ResultLength != Length)
		{
			ASSERT(ResultLength == Length);

			KeBugCheckEx(0xc0,FdoExt->BaseBus,Slot.u.AsULONG,Offset,Read);
		}

		return ResultLength;
	}

	ASSERT(RootFdoExt->BusHandler);

	ASSERT(!PciAssignBusNumbers);

	PPCIBUSDATA BusData									= static_cast<PPCIBUSDATA>(FdoExt->BusHandler->BusData);

	PciReadWriteConfig Function							= Read ? BusData->ReadConfig : BusData->WriteConfig;

	Function(RootFdoExt->BusHandler,Slot,Buffer,Offset,Length);

	return Length;
}

//
// external read device config
//
NTSTATUS PciExternalReadDeviceConfig(__in PPCI_PDO_EXTENSION PdoExt,__in PVOID Buffer,__in ULONG Offset,__in ULONG Length)
{
	PCI_COMMON_CONFIG LocalConfig;

	if(Offset + Length > sizeof(LocalConfig))
		return STATUS_INVALID_DEVICE_REQUEST;

	PciReadDeviceConfig(PdoExt,Add2Ptr(&LocalConfig,Offset,PVOID),Offset,Length);

	ULONG InterruptLineOffset							= FIELD_OFFSET(PCI_COMMON_CONFIG,u.type0.InterruptLine);
	if(PdoExt->InterruptPin && Offset <= InterruptLineOffset && Offset + Length > InterruptLineOffset)
		LocalConfig.u.type0.InterruptLine				= PdoExt->AdjustedInterruptLine;

	RtlCopyMemory(Buffer,Add2Ptr(&LocalConfig,Offset,PVOID),Length);

	return STATUS_SUCCESS;
}

//
// external write device config [checked]
//
NTSTATUS PciExternalWriteDeviceConfig(__in PPCI_PDO_EXTENSION PdoExt,__in PVOID Buffer,__in ULONG Offset,__in ULONG Length)
{
	PCI_COMMON_CONFIG LocalConfig;

	if(Offset + Length > sizeof(PCI_COMMON_CONFIG))
		return STATUS_INVALID_DEVICE_REQUEST;

	NTSTATUS Status										= STATUS_SUCCESS;

	#define CONTAIN_RANGE(s1,e1,s2,e2)					(((s1) >= (s2)) ? ((s1) < (e2)) : ((e1) > (s2)))

	switch(PdoExt->HeaderType)
	{
	case PCI_DEVICE_TYPE:
		{
			//
			// attempt to write bar
			//
			if(CONTAIN_RANGE(Offset,Offset + Length,FIELD_OFFSET(PCI_COMMON_CONFIG,u.type0.BaseAddresses),FIELD_OFFSET(PCI_COMMON_CONFIG,u.type0.CIS)))
				Status									= STATUS_INVALID_DEVICE_REQUEST;

			//
			// attempt to write rom address
			//
			if(CONTAIN_RANGE(Offset,Offset + Length,FIELD_OFFSET(PCI_COMMON_CONFIG,u.type0.ROMBaseAddress),FIELD_OFFSET(PCI_COMMON_CONFIG,u.type0.CapabilitiesPtr)))
				Status									= STATUS_INVALID_DEVICE_REQUEST;
		}
		break;

	case PCI_BRIDGE_TYPE:
		{
			//
			// attempt to write bar and bus number
			//
			if(CONTAIN_RANGE(Offset,Offset + Length,FIELD_OFFSET(PCI_COMMON_CONFIG,u.type1.BaseAddresses),FIELD_OFFSET(PCI_COMMON_CONFIG,u.type1.SecondaryLatency)))
				Status									= STATUS_INVALID_DEVICE_REQUEST;

			//
			// attempt to write io base
			//
			if(CONTAIN_RANGE(Offset,Offset + Length,FIELD_OFFSET(PCI_COMMON_CONFIG,u.type1.IOBase),FIELD_OFFSET(PCI_COMMON_CONFIG,u.type1.SecondaryStatus)))
				Status									= STATUS_INVALID_DEVICE_REQUEST;

			//
			// attemp to write memory
			//
			if(CONTAIN_RANGE(Offset,Offset + Length,FIELD_OFFSET(PCI_COMMON_CONFIG,u.type1.MemoryBase),FIELD_OFFSET(PCI_COMMON_CONFIG,u.type1.CapabilitiesPtr)))
				Status									= STATUS_INVALID_DEVICE_REQUEST;

			//
			// attemp to write rom address
			//
			if(CONTAIN_RANGE(Offset,Offset + Length,FIELD_OFFSET(PCI_COMMON_CONFIG,u.type1.ROMBaseAddress),FIELD_OFFSET(PCI_COMMON_CONFIG,u.type1.InterruptLine)))
				Status									= STATUS_INVALID_DEVICE_REQUEST;
		}
		break;

	case PCI_CARDBUS_BRIDGE_TYPE:
		{
			//
			// attempt to write socket address
			//
			if(CONTAIN_RANGE(Offset,Offset + Length,FIELD_OFFSET(PCI_COMMON_CONFIG,u.type2),FIELD_OFFSET(PCI_COMMON_CONFIG,u.type2.CapabilitiesPtr)))
				Status									= STATUS_INVALID_DEVICE_REQUEST;

			//
			// attempt to write bus number
			//
			if(CONTAIN_RANGE(Offset,Offset + Length,FIELD_OFFSET(PCI_COMMON_CONFIG,u.type2.PrimaryBus),FIELD_OFFSET(PCI_COMMON_CONFIG,u.type2.SecondaryStatus)))
				Status									= STATUS_INVALID_DEVICE_REQUEST;

			//
			// attemp to write range
			//
			if(CONTAIN_RANGE(Offset,Offset + Length,FIELD_OFFSET(PCI_COMMON_CONFIG,u.type2.Range),FIELD_OFFSET(PCI_COMMON_CONFIG,u.type2.InterruptLine)))
				Status									= STATUS_INVALID_DEVICE_REQUEST;
		}
		break;

	default:
		break;
	}

	#undef CONTAIN_RANGE

	if(!NT_SUCCESS(Status))
	{
		PDEVICE_OBJECT Pdo								= PdoExt->PhysicalDeviceObject;
		PVERIFIER_FAILURE_DATA Data						= PciVerifierRetrieveFailureData(3);
		ASSERT(Data);
		VfFailDeviceNode(Pdo,0xf6,3,Data->Offset4,&Data->Offset8,Data->FailureMessage,"%DevObj%Ulong%Ulong",Pdo,Offset,Length);
	}

	RtlCopyMemory(Add2Ptr(&LocalConfig,Offset,PVOID),Buffer,Length);

	ULONG InterruptLineOffset							= FIELD_OFFSET(PCI_COMMON_CONFIG,u.type0.InterruptLine);
	if(PdoExt->InterruptPin && Offset <= InterruptLineOffset && Offset + Length > InterruptLineOffset)
		LocalConfig.u.type0.InterruptLine				= PdoExt->AdjustedInterruptLine;

	PciWriteDeviceConfig(PdoExt,Add2Ptr(&LocalConfig,Offset,PVOID),Offset,Length);

	return STATUS_SUCCESS;
}

//
// get adjusted interrupt line [checked]
//
UCHAR PciGetAdjustedInterruptLine(__in PPCI_PDO_EXTENSION PdoExt)
{
	if(!PdoExt->InterruptPin)
		return 0;

	UCHAR Line											= 0;
	ULONG Offset										= FIELD_OFFSET(PCI_COMMON_HEADER,u.type0.InterruptLine);
	ULONG Length										= sizeof(Line);

	if(!HalGetBusDataByOffset(PCIConfiguration,PdoExt->ParentFdoExtension->BaseBus,PdoExt->Slot.u.AsULONG,&Line,Offset,Length))
		Line											= PdoExt->RawInterruptLine;

	return Line;
}


text:
package org.cfeclipse.cfml.preferences;

import org.cfeclipse.cfml.CFMLPlugin;
import org.eclipse.jface.preference.FieldEditorPreferencePage;
import org.eclipse.jface.preference.StringFieldEditor;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;

public class SnipExPreferencePage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage {

	CFMLPreferenceManager cfmlpm;

	public SnipExPreferencePage() {
		super(GRID);
		setPreferenceStore(CFMLPlugin.getDefault().getPreferenceStore());
		setDescription("These preferences will allow you to customize the what SnipEx servers will be aggregated in your snippet view.\n\n");
		cfmlpm = new CFMLPreferenceManager();
	}

	protected void createFieldEditors() {
		addField(new StringFieldEditor(SnipExPreferenceConstants.P_SNIPEX_URL1,"URL 1",getFieldEditorParent()));
		addField(new StringFieldEditor(SnipExPreferenceConstants.P_SNIPEX_URL2,"URL 2",getFieldEditorParent()));
		addField(new StringFieldEditor(SnipExPreferenceConstants.P_SNIPEX_URL3,"URL 3",getFieldEditorParent()));
		addField(new StringFieldEditor(SnipExPreferenceConstants.P_SNIPEX_URL4,"URL 4",getFieldEditorParent()));
		addField(new StringFieldEditor(SnipExPreferenceConstants.P_SNIPEX_URL5,"URL 5",getFieldEditorParent()));
		addField(new StringFieldEditor(SnipExPreferenceConstants.P_SNIPEX_URL6,"URL 6",getFieldEditorParent()));
		addField(new StringFieldEditor(SnipExPreferenceConstants.P_SNIPEX_URL7,"URL 7",getFieldEditorParent()));
		addField(new StringFieldEditor(SnipExPreferenceConstants.P_SNIPEX_URL8,"URL 8",getFieldEditorParent()));

	}

	public void init(IWorkbench workbench) {}

}


text:
from __future__ import division, print_function, absolute_import

import unittest

import numpy as np
from sprocket.util.delta import delta, construct_static_and_delta_matrix

class DeltaFunctionsTest(unittest.TestCase):

    def test_delta(self):
        data1d = np.random.rand(100)
        delta1d = delta(data1d)
        assert len(data1d) == len(delta1d)

        data2d = data1d.reshape(50, 2)
        delta2d = delta(data2d)
        assert delta2d.shape[0] == data2d.shape[0]
        assert delta2d.shape[1] == data2d.shape[1]

    def test_construct_W_matrix(self):
        T, D = 100, 4
        W = construct_static_and_delta_matrix(T, D)
        assert W.shape[0] == 2 * T * D
        assert W.shape[1] == T * D


text:
<?php

use Phphilosophy\Autoloader;
use Phphilosophy\Application\Config;

// Require the autoload and the config file
require __DIR__.'/../framework/Autoloader.php';
require __DIR__.'/../application/configs/application.php';
require __DIR__.'/../application/configs/database.php';

// create the autoload instance
$autoload = new Autoloader();

// Add namespace prefixes
$autoload->addNamespace('Phphilosophy', __DIR__.'/../framework/');
$autoload->addNamespace($configs['app.name'].'\\Model', __DIR__.'/../application/models/');
$autoload->addNamespace($configs['app.name'].'\\Guard', __DIR__.'/../application/guards/');
$autoload->addNamespace($configs['app.name'].'\\Controller', __DIR__.'/../application/controllers/');
$autoload->addNamespace($configs['app.name'].'\\Library', __DIR__.'/../application/libraries/');

// register the autoloader
$autoload->register();

// Add config values
Config::set('database', $database);
Config::set('app.name', $configs['app.name']);
Config::set('app.view_ext', $configs['app.view_ext']);


text:
import flux from 'flux-react';

const actions = flux.createActions([
    'toggleTextFieldStatus',
    'startLoading',
    'endLoading',
    'selectMenuItem',
    'hoverMenuItem',
    'dehoverMenuItem',
    'toggleCompatibility',
    'addChip',
    'notify',
    'showBackButton',
    'hideBackButton'
]);

export default actions;


text:
#include <boost/serialization/shared_ptr.hpp>

#include <deque>

struct PropertyItem
{
    PropertyItem():positions(new std::deque<unsigned int>){}
    boost::shared_ptr<std::deque<unsigned int> > positions;
    size_t tf;
};

#endif


text:
const handlers = {
  NO: require('./norwegian')
}

module.exports.getRequiredFields = function (countryCode) {
  if (handlers.hasOwnProperty(countryCode)) {
    return handlers[countryCode].requiredFields
  } else {
    return {
      error: 'Unknown country code ' + countryCode
    }
  }
}

module.exports.getData = function (params) {
  if (handlers.hasOwnProperty(params.countryCode)) {
    return handlers[params.countryCode].getData(params)
  } else {
    return {
      error: 'Unknown country code ' + params.countryCode
    }
  }
}


text:
package net.geforcemods.securitycraft.items;

import java.util.Random;

import net.geforcemods.securitycraft.ConfigHandler;
import net.geforcemods.securitycraft.SCContent;
import net.geforcemods.securitycraft.inventory.BriefcaseContainer;
import net.geforcemods.securitycraft.inventory.BriefcaseMenu;
import net.geforcemods.securitycraft.util.PlayerUtils;
import net.geforcemods.securitycraft.util.Utils;
import net.minecraft.ChatFormatting;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResultHolder;
import net.minecraft.world.MenuProvider;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Rarity;
import net.minecraft.world.item.enchantment.Enchantment;
import net.minecraft.world.level.Level;
import net.minecraftforge.network.NetworkHooks;

public class CodebreakerItem extends Item {
	public CodebreakerItem(Item.Properties properties) {
		super(properties);
	}

	@Override
	public InteractionResultHolder<ItemStack> use(Level level, Player player, InteractionHand hand) {
		ItemStack codebreaker = player.getItemInHand(hand);

		if (hand == InteractionHand.MAIN_HAND && player.getOffhandItem().getItem() == SCContent.BRIEFCASE.get()) {
			double chance = ConfigHandler.SERVER.codebreakerChance.get();

			if (chance < 0.0D)
				PlayerUtils.sendMessageToPlayer(player, Utils.localize(SCContent.BRIEFCASE.get().getDescriptionId()), Utils.localize("messages.securitycraft:codebreakerDisabled"), ChatFormatting.RED);
			else {
				codebreaker.hurtAndBreak(1, player, p -> p.broadcastBreakEvent(hand));

				if (!level.isClientSide && (player.isCreative() || new Random().nextDouble() < chance)) {
					ItemStack briefcase = player.getOffhandItem();

					NetworkHooks.openScreen((ServerPlayer) player, new MenuProvider() {
						@Override
						public AbstractContainerMenu createMenu(int windowId, Inventory inv, Player player) {
							return new BriefcaseMenu(windowId, inv, new BriefcaseContainer(briefcase));
						}

						@Override
						public Component getDisplayName() {
							return briefcase.getHoverName();
						}
					}, player.blockPosition());
				}
				else
					PlayerUtils.sendMessageToPlayer(player, Component.translatable(SCContent.CODEBREAKER.get().getDescriptionId()), Utils.localize("messages.securitycraft:codebreaker.failed"), ChatFormatting.RED);
			}

			return InteractionResultHolder.success(codebreaker);
		}

		return InteractionResultHolder.pass(codebreaker);
	}

	@Override
	public boolean isFoil(ItemStack stack) {
		return true;
	}

	@Override
	public Rarity getRarity(ItemStack stack) {
		return Rarity.RARE;
	}

	@Override
	public boolean canApplyAtEnchantingTable(ItemStack stack, Enchantment enchantment) {
		return false;
	}

	@Override
	public boolean isBookEnchantable(ItemStack stack, ItemStack book) {
		return false;
	}

	@Override
	public boolean isEnchantable(ItemStack stack) {
		return false;
	}
}


text:
FROM yrpri/base
MAINTAINER Robert Vidar Bjarnason <robert@citizens.is>

RUN echo 'version 0.15'

ENV DEBIAN_FRONTEND noninteractive

RUN apt-get -qq update
RUN apt-get -yqq upgrade
RUN apt-get install -y python-software-properties python
RUN add-apt-repository ppa:chris-lea/node.js
RUN apt-get update
RUN apt-get -yqq install openssl git nodejs

RUN cd /root;git clone https://github.com/rbjarnason/KiwiIRC.git

ADD supervisor.conf /etc/supervisor/conf.d/kiwiirc.conf

VOLUME ["/etc/kiwiirc"]

EXPOSE 443

CMD ["/usr/bin/supervisord"]


text:
ActiveRecord::Schema.define(version: 20160620190105) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "repositories", force: :cascade do |t|
    t.string   "name"
    t.integer  "user_id"
    t.datetime "repo_created_at"
  end

  add_index "repositories", ["user_id"], name: "index_repositories_on_user_id", using: :btree

  create_table "users", force: :cascade do |t|
    t.string  "login"
    t.string  "name"
    t.integer "stars", default: 0
  end

  add_foreign_key "repositories", "users"
end


text:
package hr.fer.zemris.jcms.web.navig.builders.course.applications;

import hr.fer.zemris.jcms.service.has.HasCourseInstance;

import hr.fer.zemris.jcms.web.actions.data.support.AbstractActionData;
import hr.fer.zemris.jcms.web.navig.Navigation;
import hr.fer.zemris.jcms.web.navig.NavigationBuilder;
import hr.fer.zemris.jcms.web.navig.TextNavigationItem;

public class ApplicationListStudentsBuilder extends NavigationBuilder {

	public static void build(Navigation navig, AbstractActionData actionData, boolean root) {
		HasCourseInstance d = (HasCourseInstance)actionData;
		navig.suggestPageTitle(actionData.getMessageLogger().getText("Navigation.courseHome") + " " +d.getCourseInstance().getCourse().getName());
		ApplicationMainBuilder.build(navig, actionData, false);

		navig.getNavigationBar("m2")
			.addItem(
				new TextNavigationItem("Navigation.applicationListStudents")
			);

	}

}


text:
//
//  AZTabBar.h
//  AZAppearanceKit
//
//  Created by Victor Pena Placer on 3/1/12.
//  Copyright (c) 2012 Victor Pena Placer. All rights reserved.
//  Copyright (c) 2012 Zachary Waldowski. All rights reserved.
//

@class AZGradient;

/** `AZTabBar` is a subclass of `UITabBar` that removes the
 glossy effect and lets you customize its colors.

 You can change the tab bar appearance as follows:

 - gradient
 - separator line volor

 */
@interface AZTabBar : UITabBar

/** Specifies the toolbar shadow's opacity.

 By default is `0.5`. */
@property (nonatomic, assign) CGFloat shadowOpacity;

/** Specifies the gradient's start color.

 By default, it is a gradient made up of black tones. */
@property (nonatomic, strong) AZGradient *gradient;

/** Specifies the top separator's color.

 By default is a black tone. */
@property (nonatomic, strong) UIColor *separatorLineColor;

@end


text:
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
 * Copyright (c) 2009 IITP RAS
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation;
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * This is an example script for AODV manet routing protocol.
 *
 * Authors: Pavel Boyko <boyko@iitp.ru>
 */

#include "ns3/aodv-module.h"
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/internet-module.h"
#include "ns3/mobility-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/wifi-module.h"
#include "ns3/v4ping-helper.h"
#include <iostream>
#include <cmath>

using namespace ns3;

/**
 * \brief Test script.
 *
 * This script creates 1-dimensional grid topology and then ping last node from the first one:
 *
 * [10.0.0.1] <-- step --> [10.0.0.2] <-- step --> [10.0.0.3] <-- step --> [10.0.0.4]
 *
 * ping 10.0.0.4
 */
class AodvExample
{
public:
  AodvExample ();
  /// Configure script parameters, \return true on successful configuration
  bool Configure (int argc, char **argv);
  /// Run simulation
  void Run ();
  /// Report results
  void Report (std::ostream & os);

private:
  ///\name parameters
  //\{
  /// Number of nodes
  uint32_t size;
  /// Distance between nodes, meters
  double step;
  /// Simulation time, seconds
  double totalTime;
  /// Write per-device PCAP traces if true
  bool pcap;
  /// Print routes if true
  bool printRoutes;
  //\}

  ///\name network
  //\{
  NodeContainer nodes;
  NetDeviceContainer devices;
  Ipv4InterfaceContainer interfaces;
  //\}

private:
  void CreateNodes ();
  void CreateDevices ();
  void InstallInternetStack ();
  void InstallApplications ();
};

int main (int argc, char **argv)
{
  AodvExample test;
  if (!test.Configure (argc, argv))
    NS_FATAL_ERROR ("Configuration failed. Aborted.");

  test.Run ();
  test.Report (std::cout);
  return 0;
}

//-----------------------------------------------------------------------------
AodvExample::AodvExample () :
  size (10),
  step (100),
  totalTime (10),
  pcap (true),
  printRoutes (true)
{
}

bool
AodvExample::Configure (int argc, char **argv)
{
  // Enable AODV logs by default. Comment this if too noisy
  // LogComponentEnable("AodvRoutingProtocol", LOG_LEVEL_ALL);

  SeedManager::SetSeed (12345);
  CommandLine cmd;

  cmd.AddValue ("pcap", "Write PCAP traces.", pcap);
  cmd.AddValue ("printRoutes", "Print routing table dumps.", printRoutes);
  cmd.AddValue ("size", "Number of nodes.", size);
  cmd.AddValue ("time", "Simulation time, s.", totalTime);
  cmd.AddValue ("step", "Grid step, m", step);

  cmd.Parse (argc, argv);
  return true;
}

void
AodvExample::Run ()
{
//  Config::SetDefault ("ns3::WifiRemoteStationManager::RtsCtsThreshold", UintegerValue (1)); // enable rts cts all the time.
  CreateNodes ();
  CreateDevices ();
  InstallInternetStack ();
  InstallApplications ();

  std::cout << "Starting simulation for " << totalTime << " s ...\n";

  Simulator::Stop (Seconds (totalTime));
  Simulator::Run ();
  Simulator::Destroy ();
}

void
AodvExample::Report (std::ostream &)
{
}

void
AodvExample::CreateNodes ()
{
  std::cout << "Creating " << (unsigned)size << " nodes " << step << " m apart.\n";
  nodes.Create (size);
  // Name nodes
  for (uint32_t i = 0; i < size; ++i)
    {
      std::ostringstream os;
      os << "node-" << i;
      Names::Add (os.str (), nodes.Get (i));
    }
  // Create static grid
  MobilityHelper mobility;
  mobility.SetPositionAllocator ("ns3::GridPositionAllocator",
                                 "MinX", DoubleValue (0.0),
                                 "MinY", DoubleValue (0.0),
                                 "DeltaX", DoubleValue (step),
                                 "DeltaY", DoubleValue (0),
                                 "GridWidth", UintegerValue (size),
                                 "LayoutType", StringValue ("RowFirst"));
  mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");
  mobility.Install (nodes);
}

void
AodvExample::CreateDevices ()
{
  NqosWifiMacHelper wifiMac = NqosWifiMacHelper::Default ();
  wifiMac.SetType ("ns3::AdhocWifiMac");
  YansWifiPhyHelper wifiPhy = YansWifiPhyHelper::Default ();
  YansWifiChannelHelper wifiChannel = YansWifiChannelHelper::Default ();
  wifiPhy.SetChannel (wifiChannel.Create ());
  WifiHelper wifi = WifiHelper::Default ();
  wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager", "DataMode", StringValue ("OfdmRate6Mbps"), "RtsCtsThreshold", UintegerValue (0));
  devices = wifi.Install (wifiPhy, wifiMac, nodes);

  if (pcap)
    {
      wifiPhy.EnablePcapAll (std::string ("aodv"));
    }
}

void
AodvExample::InstallInternetStack ()
{
  AodvHelper aodv;
  // you can configure AODV attributes here using aodv.Set(name, value)
  InternetStackHelper stack;
  stack.SetRoutingHelper (aodv); // has effect on the next Install ()
  stack.Install (nodes);
  Ipv4AddressHelper address;
  address.SetBase ("10.0.0.0", "255.0.0.0");
  interfaces = address.Assign (devices);

  if (printRoutes)
    {
      Ptr<OutputStreamWrapper> routingStream = Create<OutputStreamWrapper> ("aodv.routes", std::ios::out);
      aodv.PrintRoutingTableAllAt (Seconds (8), routingStream);
    }
}

void
AodvExample::InstallApplications ()
{
  V4PingHelper ping (interfaces.GetAddress (size - 1));
  ping.SetAttribute ("Verbose", BooleanValue (true));

  ApplicationContainer p = ping.Install (nodes.Get (0));
  p.Start (Seconds (0));
  p.Stop (Seconds (totalTime) - Seconds (0.001));

  // move node away
  Ptr<Node> node = nodes.Get (size/2);
  Ptr<MobilityModel> mob = node->GetObject<MobilityModel> ();
  Simulator::Schedule (Seconds (totalTime/3), &MobilityModel::SetPosition, mob, Vector (1e5, 1e5, 1e5));
}


text:
struct WordItem
{
	QString word;
	QString def;
	int lineno;
};

class WordsModel : public QAbstractTableModel
{
	Q_OBJECT
public:
	enum Cols { Word, Def, Lineno, NCols };
	Q_ENUM(Cols)
	WordsModel(QObject *parent);
	~WordsModel();
	void save();
	void sort();
	void analyse(QString source);
	const QVector<WordItem> &words() const { return m_data; }
	// QAbstractItemModel interface
public:
	virtual QModelIndex index(int row, int column, const QModelIndex &parent) const;
	virtual int rowCount(const QModelIndex &) const;
	virtual int columnCount(const QModelIndex &) const;
	virtual bool hasChildren(const QModelIndex &) const;
	virtual QVariant data(const QModelIndex &index, int role) const;
	virtual QVariant headerData(int section, Qt::Orientation orientation, int role) const;
	virtual Qt::ItemFlags flags(const QModelIndex &) const;
	void clear();
protected:
private:
	QVector<WordItem> m_data;
	const QStringList m_header;
};

#endif // WORDSMODEL_H


text:
#ifndef TENSORFLOW_CONTRIB_TENSORRT_RESOURCES_TRT_RESOURCES_H_
#define TENSORFLOW_CONTRIB_TENSORRT_RESOURCES_TRT_RESOURCES_H_

#include <list>
#include <sstream>
#include <string>
#include <thread>
#include <vector>

#include "tensorflow/contrib/tensorrt/convert/utils.h"
#include "tensorflow/contrib/tensorrt/log/trt_logger.h"
#include "tensorflow/contrib/tensorrt/resources/trt_allocator.h"
#include "tensorflow/contrib/tensorrt/resources/trt_int8_calibrator.h"
#include "tensorflow/core/framework/resource_mgr.h"

#if GOOGLE_CUDA
#if GOOGLE_TENSORRT

#include "tensorrt/include/NvInfer.h"

namespace tensorflow {
namespace tensorrt {

class TRTCalibrationResource : public tensorflow::ResourceBase {
 public:
  ~TRTCalibrationResource() {
    VLOG(0) << "Destroying Calibration Resource " << std::endl << DebugString();
    builder_.reset();
    engine_.reset();
    // We need to manually destroy the builder and engine before the allocator
    // is destroyed.
    allocator_.reset();
  }

  string DebugString() override {
    std::stringstream oss;
    using std::dec;
    using std::endl;
    using std::hex;
    oss << " Calibrator = " << hex << calibrator_.get() << dec << endl
        << " Builder    = " << hex << builder_.get() << dec << endl
        << " Engine     = " << hex << engine_.get() << dec << endl
        << " Logger     = " << hex << &logger_ << dec << endl
        << " Allocator  = " << hex << allocator_.get() << dec << endl
        << " Thread     = " << hex << thr_.get() << dec << endl;
    return oss.str();
  }

  std::unique_ptr<TRTInt8Calibrator> calibrator_;
  TrtUniquePtrType<nvinfer1::IBuilder> builder_;
  TrtUniquePtrType<nvinfer1::ICudaEngine> engine_;
  std::unique_ptr<TRTBaseAllocator> allocator_;
  tensorflow::tensorrt::Logger logger_;
  // TODO(sami): Use threadpool threads!
  std::unique_ptr<std::thread> thr_;
};

class TRTWeightStore {
 public:
  TRTWeightStore() {}

  virtual ~TRTWeightStore() { VLOG(1) << "Destroying store" << DebugString(); }

  string DebugString() {
    std::stringstream oss;
    size_t len_bytes = 0;
    for (const auto& v : store_) {
      len_bytes += v.size() * sizeof(uint8_t);
    }
    oss << " Number of entries     = " << store_.size() << std::endl
        << " Total number of bytes = "
        << store_.size() * sizeof(std::vector<uint8_t>) + len_bytes
        << std::endl;
    return oss.str();
  }

  std::list<std::vector<uint8_t>> store_;
};

}  // namespace tensorrt
}  // namespace tensorflow

#endif
#endif
#endif  // TENSORFLOW_CONTRIB_TENSORRT_RESOURCES_TRT_RESOURCES_H_


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

package com.github.ipaas.ifw.core.health;

/**
 *
 * 缺省Heavy检查实现类
 * @author Chenql
 *
 */
public class GenericBizCheckImpl implements BizCheck {

    @Override
    public String checkBiz() {
        return "1";
    }

}