text:
package com.winsun.fruitmix.parser;

import com.winsun.fruitmix.model.Media;
import com.winsun.fruitmix.util.LocalCache;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * Created by Administrator on 2016/8/31.
 */
public class RemoteMediaParser implements RemoteDataParser<Media> {

    @Override
    public List<Media> parse(String json) {

        List<Media> medias = new ArrayList<>();

        String time;
        JSONArray jsonArray;
        JSONObject itemRaw;
        Media media;

        try {
            jsonArray = new JSONArray(json);

            for (int i = 0; i < jsonArray.length(); i++) {
                itemRaw = jsonArray.getJSONObject(i);
                if (itemRaw.getString("kind").equals("image")) {

                    media = new Media();

                    media.setUuid(itemRaw.getString("hash"));
                    media.setTime("1916-01-01 00:00:00");
                    if (itemRaw.has("width")) {
                        media.setWidth(itemRaw.getString("width"));
                        media.setHeight(itemRaw.getString("height"));
                    } else if (itemRaw.getJSONObject("detail").has("width")) {
                        media.setWidth(itemRaw.getJSONObject("detail").getString("width"));
                        media.setHeight(itemRaw.getJSONObject("detail").getString("height"));
                    } else {
                        media.setWidth(itemRaw.getJSONObject("detail").getJSONObject("exif").getString("ExifImageWidth"));
                        media.setHeight(itemRaw.getJSONObject("detail").getJSONObject("exif").getString("ExifImageHeight"));
                        if (itemRaw.getJSONObject("detail").has("exif") && itemRaw.getJSONObject("detail").getJSONObject("exif").has("CreateDate")) {
                            time = itemRaw.getJSONObject("detail").getJSONObject("exif").getString("CreateDate");
                            media.setTime(time.substring(0, 4) + "-" + time.substring(5, 7) + "-" + time.substring(8));
                        } else media.setTime("1916-01-01 00:00:00");
                    }

                    medias.add(media);

                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return medias;
    }
}


text:
package com.espirit.moddev.examples.uxbridge.newsdrilldown;

/*
 */

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.Index;

// TODO: Auto-generated Javadoc
/**
 * The Class NewsMetaCategory which will be persisted to the table 'metaCategory'.
 */
@Entity(name = "metaCategory")
@Table(name = "metaCategory")
@org.hibernate.annotations.Table(appliesTo = "metaCategory", indexes = { @Index(name = "IDX_fsid_lang_3", columnNames = {
		"fs_id", "language" }) })
public class NewsMetaCategory {

	/** The name. */
	@Column(length = 1024)
	private String name;

	/** The fs_id. */
	@Index(name = "fsidindex3")
	private Long fs_id;

	/** The language. */
	private String language;

	/** The lastmodified. */
	private long lastmodified;

	/** The id. */
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private Long id;

	/** The version - needed for compatibility with grails. */
	private int version = 0;

	/**
	 * Instantiates a new news meta category.
	 */
	public NewsMetaCategory() {
	}

	/**
	 * Gets the name.
	 *
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * Sets the name.
	 *
	 * @param name the new name
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * Gets the fs_id.
	 *
	 * @return the fs_id
	 */
	public Long getFs_id() {
		return fs_id;
	}

	/**
	 * Sets the fs_id.
	 *
	 * @param fs_id the new fs_id
	 */
	public void setFs_id(Long fs_id) {
		this.fs_id = fs_id;
	}

	/**
	 * Gets the language.
	 *
	 * @return the language
	 */
	public String getLanguage() {
		return language;
	}

	/**
	 * Sets the language.
	 *
	 * @param language the new language
	 */
	public void setLanguage(String language) {
		this.language = language;
	}

	/**
	 * Gets the id.
	 *
	 * @return the id
	 */
	public Long getId() {
		return id;
	}

	/**
	 * Sets the id.
	 *
	 * @param id the new id
	 */
	public void setId(Long id) {
		this.id = id;
	}

	/**
	 * Gets the version.
	 *
	 * @return the version
	 */
	public int getVersion() {
		return version;
	}

	/**
	 * Sets the version.
	 *
	 * @param version the new version
	 */
	public void setVersion(int version) {
		this.version = version;
	}

	/**
	 * Gets the lastmodified.
	 *
	 * @return the lastmodified
	 */
	public long getLastmodified() {
		return lastmodified;
	}

	/**
	 * Sets the lastmodified.
	 *
	 * @param lastmodified the new lastmodified
	 */
	public void setLastmodified(long lastmodified) {
		this.lastmodified = lastmodified;
	}

	@Override
	public boolean equals(Object obj) {
		if (!(obj instanceof NewsMetaCategory)) {
			return false;
		}
		NewsMetaCategory mc = (NewsMetaCategory)obj;
		if (mc.fs_id == this.fs_id && mc.language.equals(this.language)) {
			return true;
		}
		return false;
	}

	@Override
	public int hashCode() {
		int hash = 1;
		hash = hash * 31 + this.fs_id.hashCode();
		hash = hash * 31 + this.language.hashCode();

		return hash;
	}
}

redpajama_set_name: RedPajamaGithub


text:
<?php namespace Fisharebest\Localization\Variant;

interface VariantInterface {
	/**
	 * The code for this variant.
	 *
	 * @return string
	 */
	public function code();
}


text:
FOUNDATION_EXPORT double SemoContentVersionNumber;

//! Project version string for SemoContent.
FOUNDATION_EXPORT const unsigned char SemoContentVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <SemoContent/PublicHeader.h>


text:
package interpreter

import (
	"fmt"
	"github.com/Azer0s/Hummus/parser"
)

const (
	// BUILTIN_MATH the built in math system function
	BUILTIN_MATH string = "--builtin-do-math!"
	// BUILTIN_COMPARE comparison functions
	BUILTIN_COMPARE string = "--builtin-do-compare!"
	// BUILTIN_COMPARE_ARITHMETIC arithmetic comparison functions
	BUILTIN_COMPARE_ARITHMETIC string = "--builtin-do-compare-arithmetic!"
	// BUILTIN_BOOL boolean algebra functions
	BUILTIN_BOOL string = "--builtin-do-bool!"
	// BUILTIN_BITWISE bitwise functions
	BUILTIN_BITWISE string = "--builtin-do-bitwise!"
)

func builtInMath(node parser.Node, variables *map[string]Node) Node {
	args := resolve(node.Arguments, variables)

	mode := args[0].Value.(string)

	if mode == "-" && args[1].NodeType == NODETYPE_INT {
		return Node{
			Value:    -args[1].Value.(int),
			NodeType: NODETYPE_INT,
		}
	}

	if mode == "-" && args[1].NodeType == NODETYPE_FLOAT {
		return Node{
			Value:    -args[1].Value.(float64),
			NodeType: NODETYPE_FLOAT,
		}
	}

	vals := args[1].Value.(ListNode)

	if len(vals.Values) < 2 {
		panic(fmt.Sprintf("Arithmetic operations expect at least 2 arguments! (line %d)", node.Token.Line))
	}

	//If any arg is a float, we switch to float mode
	//Only ints and floats allowed

	floatMode := false

	for _, value := range vals.Values {
		if value.NodeType != NODETYPE_FLOAT && value.NodeType != NODETYPE_INT {
			panic(fmt.Sprintf("Only float or int allowed for arithmetic operations! (line %d)", node.Token.Line))
		}

		if value.NodeType == NODETYPE_FLOAT {
			floatMode = true
			break
		}
	}

	if floatMode {
		f := make([]float64, 0)

		for _, value := range vals.Values {
			if value.NodeType == NODETYPE_INT {
				f = append(f, float64(value.Value.(int)))
			} else {
				f = append(f, value.Value.(float64))
			}
		}

		return doFloatCalculation(mode, f)
	}

	i := make([]int, 0)

	for _, value := range vals.Values {
		i = append(i, value.Value.(int))
	}

	return doIntCalculation(mode, i)
}

func builtInCompare(node parser.Node, variables *map[string]Node) Node {
	args := resolve(node.Arguments, variables)

	mode := args[0].Value.(string)

	switch mode {
	case "/=":
		return Node{
			Value:    args[1].Value != args[2].Value,
			NodeType: NODETYPE_BOOL,
		}
	case "=":
		return Node{
			Value:    args[1].Value == args[2].Value,
			NodeType: NODETYPE_BOOL,
		}
	case "min":
		if args[1].NodeType != NODETYPE_LIST {
			panic(BUILTIN_COMPARE + " :min only accepts lists!")
		}

		list := args[1].Value.(ListNode).Values
		min := list[0]

		for i := 1; i < len(list); i++ {
			if list[i].Smaller(min) {
				min = list[i]
			}
		}

		return min
	case "max":
		if args[1].NodeType != NODETYPE_LIST {
			panic(BUILTIN_COMPARE + " :max only accepts lists!")
		}

		list := args[1].Value.(ListNode).Values
		max := list[0]

		for i := 1; i < len(list); i++ {
			if list[i].Bigger(max) {
				max = list[i]
			}
		}

		return max
	default:
		panic("Unrecognized mode")
	}
}

func builtInCompareArithmetic(node parser.Node, variables *map[string]Node) Node {
	args := resolve(node.Arguments, variables)

	mode := args[0].Value.(string)
	//If any arg is a float, we switch to float mode
	//Only ints and floats allowed

	floatMode := false

	for _, value := range args[1:] {
		if value.NodeType != NODETYPE_FLOAT && value.NodeType != NODETYPE_INT {
			panic(fmt.Sprintf("Only float or int allowed for arithmetic operations! (line %d)", node.Token.Line))
		}

		if value.NodeType == NODETYPE_FLOAT {
			floatMode = true
			break
		}
	}

	if floatMode {
		f := make([]float64, 0)

		for _, value := range args[1:] {
			if value.NodeType == NODETYPE_INT {
				f = append(f, float64(value.Value.(int)))
			} else {
				f = append(f, value.Value.(float64))
			}
		}

		return doFloatCompare(mode, f)
	}

	i := make([]int, 0)

	for _, value := range args[1:] {
		i = append(i, value.Value.(int))
	}

	return doIntCompare(mode, i)
}

func builtInBool(node parser.Node, variables *map[string]Node) Node {
	args := resolve(node.Arguments, variables)

	mode := args[0].Value.(string)

	if mode == "not" {
		if args[1].NodeType != NODETYPE_BOOL {
			panic(BUILTIN_BOOL + " only accepts bools!")
		}

		return Node{
			Value:    !args[1].Value.(bool),
			NodeType: NODETYPE_BOOL,
		}
	}

	if args[1].NodeType != NODETYPE_BOOL || args[2].NodeType != NODETYPE_BOOL {
		panic(BUILTIN_BOOL + " only accepts bools!")
	}

	switch mode {
	case "and":
		return Node{
			Value:    args[1].Value.(bool) && args[2].Value.(bool),
			NodeType: NODETYPE_BOOL,
		}
	case "or":
		return Node{
			Value:    args[1].Value.(bool) || args[2].Value.(bool),
			NodeType: NODETYPE_BOOL,
		}
	default:
		panic("Unrecognized mode")
	}
}

func builtInBitwise(node parser.Node, variables *map[string]Node) Node {
	args := resolve(node.Arguments, variables)

	mode := args[0].Value.(string)

	if mode == "not" {
		if args[1].NodeType != NODETYPE_INT {
			panic(BUILTIN_BITWISE + " only accepts ints!")
		}

		return Node{
			Value:    int(^uint(args[1].Value.(int))),
			NodeType: NODETYPE_INT,
		}
	}

	if args[1].NodeType != NODETYPE_INT || args[2].NodeType != NODETYPE_INT {
		panic(BUILTIN_BITWISE + " only accepts ints!")
	}

	switch mode {
	case "and":
		return Node{
			Value:    int(uint(args[1].Value.(int)) & uint(args[2].Value.(int))),
			NodeType: NODETYPE_INT,
		}
	case "or":
		return Node{
			Value:    int(uint(args[1].Value.(int)) | uint(args[2].Value.(int))),
			NodeType: NODETYPE_INT,
		}
	case "shiftl":
		return Node{
			Value:    int(uint(args[1].Value.(int)) << uint(args[2].Value.(int))),
			NodeType: NODETYPE_INT,
		}
	case "shiftr":
		return Node{
			Value:    int(uint(args[1].Value.(int)) >> uint(args[2].Value.(int))),
			NodeType: NODETYPE_INT,
		}
	default:
		panic("Unrecognized mode")
	}
}

func doFloatCalculation(mode string, vals []float64) (node Node) {
	node = Node{
		Value:    vals[0],
		NodeType: NODETYPE_FLOAT,
	}

	switch mode {
	case "*":
		for i := 1; i < len(vals); i++ {
			node.Value = node.Value.(float64) * vals[i]
		}
		break
	case "/":
		for i := 1; i < len(vals); i++ {
			node.Value = node.Value.(float64) / vals[i]
		}
		break
	case "+":
		for i := 1; i < len(vals); i++ {
			node.Value = node.Value.(float64) + vals[i]
		}
		break
	case "-":
		for i := 1; i < len(vals); i++ {
			node.Value = node.Value.(float64) - vals[i]
		}
		break
	}

	return
}

func doIntCalculation(mode string, vals []int) (node Node) {
	node = Node{
		Value:    vals[0],
		NodeType: NODETYPE_INT,
	}

	switch mode {
	case "*":
		for i := 1; i < len(vals); i++ {
			node.Value = node.Value.(int) * vals[i]
		}
		break
	case "/":
		for i := 1; i < len(vals); i++ {
			node.Value = node.Value.(int) / vals[i]
		}
		break
	case "+":
		for i := 1; i < len(vals); i++ {
			node.Value = node.Value.(int) + vals[i]
		}
		break
	case "-":
		for i := 1; i < len(vals); i++ {
			node.Value = node.Value.(int) - vals[i]
		}
		break
	}

	return
}

func doFloatCompare(mode string, f []float64) Node {
	switch mode {
	case "<":
		return Node{
			Value:    f[0] < f[1],
			NodeType: NODETYPE_BOOL,
		}
	case ">":
		return Node{
			Value:    f[0] > f[1],
			NodeType: NODETYPE_BOOL,
		}
	case "<=":
		return Node{
			Value:    f[0] <= f[1],
			NodeType: NODETYPE_BOOL,
		}
	case ">=":
		return Node{
			Value:    f[0] >= f[1],
			NodeType: NODETYPE_BOOL,
		}
	default:
		panic("Unrecognized mode")
	}
}

func doIntCompare(mode string, i []int) Node {
	switch mode {
	case "<":
		return Node{
			Value:    i[0] < i[1],
			NodeType: NODETYPE_BOOL,
		}
	case ">":
		return Node{
			Value:    i[0] > i[1],
			NodeType: NODETYPE_BOOL,
		}
	case "<=":
		return Node{
			Value:    i[0] <= i[1],
			NodeType: NODETYPE_BOOL,
		}
	case ">=":
		return Node{
			Value:    i[0] >= i[1],
			NodeType: NODETYPE_BOOL,
		}
	default:
		panic("Unrecognized mode")
	}
}


text:
#ifndef __FACTOR_GRAPH_DATA_GENERATOR_H__
#define __FACTOR_GRAPH_DATA_GENERATOR_H__

#include <shogun/mathematics/Math.h>
#include <shogun/lib/SGVector.h>
#include <shogun/lib/SGNDArray.h>
#include <shogun/lib/SGMatrix.h>
#include <shogun/base/DynArray.h>
#include <shogun/base/init.h>
#include <shogun/io/SGIO.h>

#include <shogun/structure/FactorGraph.h>
#include <shogun/structure/FactorGraphModel.h>
#include <shogun/structure/FactorType.h>
#include <shogun/structure/Factor.h>

#include <shogun/structure/MAPInference.h>
#include <shogun/structure/StochasticSOSVM.h>

#include <shogun/features/FactorGraphFeatures.h>
#include <shogun/labels/FactorGraphLabels.h>

namespace shogun
{
/** @brief Class CFactorGraphDataGenerator Create factor graph data for  multiple unit tests
 */
class CFactorGraphDataGenerator: public CSGObject
{
public:
	/** Constructor */
	CFactorGraphDataGenerator();

	/** @return class name */
	virtual const char* get_name() const
	{
		return "FactorGraphDataGenerator";
	}

	/** Define a simple 2 node chain graph */
	CFactorGraph* simple_chain_graph();

	/** Convert grid coordinate into 1-d index
	 *
	 * @param x grid coordinate x
	 * @param y grid coordinate y
	 * @param w grid width
	 * @return index in 1-d vector
	 */
	int32_t grid_to_index(int32_t x, int32_t y, int32_t w = 10);

	/** Truncate energy table to ensure submodurality
	 *
	 * @param A value in (0,0)
	 * @param B value in (0,1)
	 * @param C value in (1,0)
	 * @param D value in (1,1)
	 */
	void truncate_energy(float64_t &A, float64_t &B, float64_t &C, float64_t &D);

	/** Define a four nodes chain graph
	 * potentials are randomly generated
	 *
	 * @param assignment_expect expected assignment
	 * @param min_energy_expect expected minimum energies
	 * @param N size of the energy table (e.g., 2x2)
	 */
	CFactorGraph* random_chain_graph(SGVector<int> &assignment_expect, float64_t &min_energy_expect, int32_t N = 2);

	/** Define a multiple state tree graph */
	CFactorGraph* multi_state_tree_graph();

	/** Generate random data following [1]:
	 * Each example has exactly one label on.
	 * Each label has 40 related binary features.
	 * For an example, if label i is on, 4i randomly chosen features are set to 1
	 *
	 * [1] Finley, Thomas, and Thorsten Joachims.
	 * "Training structural SVMs when exact inference is intractable."
	 * Proceedings of the 25th international conference on Machine learning. ACM, 2008.
	 *
	 * @param len_label label length (10)
	 * @param len_feat feature length (40)
	 * @param size_data training data size (50)
	 * @param feats generated feature matrix
	 * @param labels generated label matrix
	 */
	void generate_data(int32_t len_label, int32_t len_feat, int32_t size_data,
	                   SGMatrix<float64_t> &feats, SGMatrix<int32_t> &labels);

	/** Get fully connected edges
	 *
	 * @param num_classes number of classes
	 * @return matrix of edge
	 */
	SGMatrix< int32_t > get_edges_full(const int32_t num_classes);

	/** Build factor graph
	 *
	 * @param feats features
	 * @param labels labels
	 * @param edge_list edge list
	 * @param v_factor_type factor types
	 * @param fg_feats features for factor graph
	 * @param fg_labels labels for factor graph
	 */
	void build_factor_graph(SGMatrix<float64_t> feats, SGMatrix<int32_t> labels,
	                        SGMatrix< int32_t > edge_list, const DynArray<CTableFactorType*> &v_factor_type,
	                        CFactorGraphFeatures* fg_feats, CFactorGraphLabels* fg_labels);

	/** Define factor type
	 *
	 * @param num_classes number of classes
	 * @param dim dimension of the feature
	 * @param num_edges number of edegs
	 * @param v_factor_type factor types
	 */
	void define_factor_types(int32_t num_classes, int32_t dim, int32_t num_edges,
	                         DynArray<CTableFactorType*> &v_factor_type);

	/** Test sosvm inference algorithm with random data
	 *
	 * @param infer_type type of inference algorithm
	 * @return average training loss (expected to be 0)
	 */
	float64_t test_sosvm(EMAPInferType infer_type);
};
}
#endif


text:
package com.lewisd.ksp.craftstats.util;

import java.io.IOException;
import java.io.PrintWriter;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;

import com.lewisd.ksp.craftstats.gamedata.loader.KerbalContext;

public abstract class AbstractMain {

    protected final KerbalContext kerbalContext;
    protected final CommandLine cmdLine;
    private Options options;

    protected AbstractMain(final KerbalContext kerbalContext) {
        this.kerbalContext = kerbalContext;
        cmdLine = null;
    }

    protected AbstractMain(final String[] args) {

        options = new Options();
        options.addOption("k", "ksp", true, "Path to KSP. Required, unless KSP_HOME environment variable is set.");
        options.addOption("h", "help", false, "Print this usage information.");

        addOptions(options);

        final CommandLineParser parser = new PosixParser();
        CommandLine cmdLine = null;
        try {
            cmdLine = parser.parse(options, args);
            checkRequired(cmdLine);
        } catch (final ParseException e) {
            System.err.println(e.getMessage());
            usage();
            System.exit(2);
        }

        if (cmdLine.hasOption("help")) {
            usage();
            System.exit(0);
        }

        this.cmdLine = cmdLine;

        try {
            kerbalContext = setupKerbalContext(cmdLine);
        } catch (final IOException e) {
            throw new RuntimeException("Unable to configure KerbalContext", e);
        }
    }

    private KerbalContext setupKerbalContext(final CommandLine cmdLine) throws IOException {
        final KerbalContext kerbalContext;
        if (cmdLine.hasOption("ksp")) {
            kerbalContext = new KerbalContext(cmdLine.getOptionValue("ksp"));
        } else {
            kerbalContext = new KerbalContext();
        }
        return kerbalContext;
    }

    protected void require(final CommandLine cmdLine, final String param) {
        if (!cmdLine.hasOption(param)) {
            System.err.println("Missing required parameter: " + param);
            usage();
            System.exit(1);
        }
    }

    protected void usage() {
        System.err.println();
        final HelpFormatter formatter = new HelpFormatter();
        final PrintWriter writer = new PrintWriter(System.err);
        formatter.printHelp(writer, 74, this.getClass().getSimpleName().toLowerCase(), null, options, 1, 3, null, true);
        writer.flush();
    }

    protected abstract void checkRequired(CommandLine cmdLine);

    protected abstract void addOptions(Options options);

}


text:
import * as CodeMirror from 'codemirror';
import 'codemirror/lib/codemirror.css';
import 'codemirror/mode/python/python';

import {
    WidgetManager
} from './manager';

import {
    Kernel
} from '@jupyterlab/services';

document.addEventListener("DOMContentLoaded", function(event) {
    var baseUrl = "https://tmp60.tmpnb.org/";
    var apiUrl = baseUrl.concat("api/spawn");
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("POST", apiUrl, true);
    xmlhttp.setRequestHeader("Content-type", "application/json");

    xmlhttp.onreadystatechange = function () {
        //Call a function when the state changes.
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            let serverUrl = baseUrl.concat(JSON.parse(xmlhttp.responseText).url);
            let wsUrl = 'ws:' + serverUrl.split(':').slice(1).join(':');

            // Connect to the notebook webserver.
            let connectionInfo = {
                baseUrl: serverUrl,
                wsUrl: wsUrl
            };
            Kernel.getSpecs(connectionInfo).then(kernelSpecs => {
                (connectionInfo as any).name = kernelSpecs.default;
                return Kernel.startNew(connectionInfo);
            }).then(kernel => {

                // Create a codemirror instance
                let code = require('../widget_code.json').join("\n");
                let inputarea = document.getElementsByClassName("inputarea")[0] as HTMLElement;
                let editor = CodeMirror(inputarea, {
                    value: code,
                    mode: "python",
                    tabSize: 4,
                    showCursorWhenSelecting: true,
                    viewportMargin: Infinity,
                    readOnly: true
                });

                // Create the widget area and widget manager
                let widgetarea = document.getElementsByClassName("widgetarea")[0];
                let manager = new WidgetManager(kernel, widgetarea);

                // Run backend code to create the widgets.  You could also create the
                // widgets in the frontend, like the other widget examples demonstrate.
                kernel.execute({ code: code });
            });
        }
    }
    xmlhttp.send();
});


text:
/* @flow */
/************************************************
 * @file  Constructor
 * @author  Isaac Suttell
 ************************************************/

/**
 * Scroll Animate Container
 *
 * @type {Object}
 */
var ScrollAnimate = function(options) {
  options = Utilities.shallowClone(options || {});
  this.options = Utilities.assign(options, this.options);

  setInterval(this.updateScrollPosition.bind(this), 15);

  // Start the loop
  this.loop();
};

/**
 * Updates the interal scroll position. This helps smooth out rough scrolls
 */
ScrollAnimate.prototype.updateScrollPosition = function() {
  // Calculate
  var moveScroll = (this.scrollPosition - this.getScrollTop()) * this.options.speed;

  if (Math.abs(moveScroll) > 0.003) {
    this.scrollPosition -= moveScroll;
  } else {
    this.scrollPosition = this.getScrollTop();
  }
};

/**
 * Default Options
 *
 * @type    {Object}
 */
ScrollAnimate.prototype.options = {
  speed: 0.3
};

/**
 * Array of elements to animate
 *
 * @type    {Array}
 */
ScrollAnimate.prototype.items = [];

/**
 * Scroller starts paused until either 'run' or 'play' is called
 *
 * @type    {Boolean}
 */
ScrollAnimate.prototype.paused = false;

/**
 * Causes the loop to pause and not update any values
 */
ScrollAnimate.prototype.pause = function() {
  this.paused = true;

  return this;
};

/**
 * Causes the loop to start and begin updating again
 */
ScrollAnimate.prototype.play = function() {
  this.paused = false;

  return this;
};

/**
 * Toggle running state
 */
ScrollAnimate.prototype.toggle = function() {
  this.paused = !this.paused;

  return this;
};

/**
 * Either sets the running state or gets it
 *
 * @param     {Boolean}    state
 *
 * @return    {Boolean}
 */
ScrollAnimate.prototype.running = function(state) {
  if (Utilities.isBoolean(state)) {
    this.paused = !state;
  } else {
    return !this.paused;
  }
};

/**
 * Clears the list of items to animate
 */
ScrollAnimate.prototype.clear = function() {
  this.items = [];

  return this;
};

/**
 * Adds a property to animate
 *
 * @param    {Object}    options    config
 */
ScrollAnimate.prototype.add = function(options) {
  var id = Utilities.uniqueId(options.$el, this.items);

  var element = new ScrollTween(id, options, this);

  this.items.push(element);

  // Chaining
  return this;
};

/**
 * Document Elemenet
 *
 * @type    {Object}
 */
var doc = document.documentElement;

/**
 * Get the scroll position of the window
 *
 * @return    {Number}
 */
ScrollAnimate.prototype.getScrollTop = function() {
  return (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);
};

/**
 * Interal scroll position that we control so we can smooth out scrolling animations
 *
 * @type {Number}
 */
ScrollAnimate.prototype.scrollPosition = 0;

/**
 * Don't rerender if don't have to
 *
 * @type    {Number}
 */
ScrollAnimate.prototype.lastScrollPosition = null;

/**
 * Upates the each item's property
 *
 * Each item will have a property value. This can either be a string or an object.
 * If it's an object the it must follow:
 * property {
 *     name: (String)              css property name e.g. 'transform'
 *     string: (String)            css value will be inserted at '%s' e.g. 'translateX(%spx)''
 * }
 */
ScrollAnimate.prototype.loop = function() {
  // Only update styles when the scroll top has changed
  if (false === this.paused && this.scrollPosition !== this.lastScrollPosition) {
    this.update();
  }
  this.lastScrollPosition = this.scrollPosition;

  // Loop
  window.requestAnimationFrame(this.loop.bind(this));
};

/**
 * Applys the CSS found in Targets
 *
 * @param    {Object}   targets    An Object array of objects
 *                                {
 *                                  $el: {jQuery}
 *                                  css: {jQuery CSS Object}
 *                                }
 */
ScrollAnimate.prototype.applyCSS = function(targets) {
  var i;
  for (i in targets) {
    if (targets.hasOwnProperty(i)) {
      targets[i].$el.css(targets[i].css);
    }
  }
};

/**
 * Update each element according to scroll top
 */
ScrollAnimate.prototype.update = function() {
  var targets = {};

  var index = -1;
  var length = this.items.length;

  var position = this.scrollPosition;

  var item;

  while (++index < length) {
    item = this.items[index];

    // The Magic. Get the current value we need to apply to the el
    item.update(position);

    // Assign the Values
    if (Utilities.isObject(item.tween)) {
      // Greensock TweenMax Support
      item.tween.progress(item.percent);
    } else if (item.options.property === 'scrollTop') {
      // Apply scroll top
      item.$el.scrollTop(item.val);
    } else {
      // CSS
      // We store an object array of css to apply so we only apply it once
      // event if there are multiple tweens per $el
      targets[item.id] = item.pushCSS(targets[item.id]);
    }

    // Clean up
    item = void 0;
  }

  /**
   * Apply CSS to targets
   */
  this.applyCSS(targets);
};

/**
 * Make the Ease functions available
 *
 * @type    {Object}
 */
ScrollAnimate.prototype.Ease = Ease;


text:
package com.tommybrettschneider.imageviewer.ui.preview;

import com.tommybrettschneider.imageviewer.ui.thumbnail.ZipEntryThumbnail;
import java.awt.Cursor;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.JComponent;
import javax.swing.TransferHandler;

public class PreviewableTransferHandler extends TransferHandler {

    private final PreviewPane previewPane;

    public PreviewableTransferHandler(PreviewPane previewPane) {
        this.previewPane = previewPane;
    }

    private boolean hasFlavor(DataFlavor[] flavors, DataFlavor target) {
        for (DataFlavor flavor : flavors) {
            if (flavor.equals(target)) {
                return true;
            }
        }
        return false;
    }

    private boolean hasFileListFlavor(DataFlavor[] flavors) {
        return hasFlavor(flavors, DataFlavor.javaFileListFlavor);
    }

    private boolean hasImageFlavor(DataFlavor[] flavors) {
        return hasFlavor(flavors, DataFlavor.imageFlavor);
    }

    private boolean hasZipEntryFlavor(DataFlavor[] flavors) {
        return hasFlavor(flavors, DataFlavor.stringFlavor);
    }

    public boolean hasAllowedFlavor(DataFlavor[] flavors) {
        return hasFileListFlavor(flavors) || hasImageFlavor(flavors);
    }

    /* (non-Javadoc)
     * @see javax.swing.TransferHandler#canImport(javax.swing.JComponent, java.awt.datatransfer.DataFlavor[])
     */
    @Override
    public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) {
        return hasFileListFlavor(transferFlavors) || hasImageFlavor(transferFlavors);
    }

    /* (non-Javadoc)
     * @see javax.swing.TransferHandler#importData(javax.swing.JComponent, java.awt.datatransfer.Transferable)
     */
    @Override
    public boolean importData(JComponent comp, Transferable t) {
        if (!canImport(comp, t.getTransferDataFlavors())) {
            return false;
        }
        if (hasAllowedFlavor(t.getTransferDataFlavors())) {
            previewPane.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
            getTransferedObjectAndSetSource(t);
        }
        return true;
    }

    private void getTransferedObjectAndSetSource(final Transferable t) {
        try {
            final URI uri = getURLFromDnD(t);
            System.out.println(uri);
            if (isSupportedImage(uri)) {
                previewPane.setSource(uri);
                System.out.println("Got image from link...");
            } else {
                System.out.println("fehler");
                throw new Exception("test");
            }
        } catch (Exception e) {
            try {
                final BufferedImage img = getImageFromDnD(t);
                previewPane.setSource(img);
                System.out.println("Got image from image...");
            } catch (Exception e3) {
                try {
                    final File file = getFileFromDnD(t);
                    previewPane.setSource(file.toURI());
                    System.out.println("Got image from file...");
                } catch (Exception e2) {
                    ZipEntryThumbnail zipThumb;
                    try {
                        zipThumb = getZipEntryFromDnD(t);
                        previewPane.setSource(zipThumb.getInputStream());
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            }
        }
    }

    protected boolean isSupportedImage(URI uri) {
        final String url = uri.getPath().toLowerCase();
        for (String readerFormatName : ImageIO.getReaderFormatNames()) {
            if (url.contains(readerFormatName.toLowerCase())) {
                return true;
            }
        }
        return false;
    }

    private ZipEntryThumbnail getZipEntryFromDnD(final Transferable t) throws UnsupportedFlavorException, IOException {
        final ZipEntryThumbnail zipEntryThumb = (ZipEntryThumbnail) t.getTransferData(DataFlavor.javaFileListFlavor);
        return zipEntryThumb;
    }

    private File getFileFromDnD(final Transferable t) throws UnsupportedFlavorException, IOException {
        final List files = new ArrayList();
        files.addAll((List) t.getTransferData(DataFlavor.javaFileListFlavor));
        files.addAll((List) t.getTransferData(DataFlavor.stringFlavor));
        return (File) files.get(0);
    }

    private URI getURLFromDnD(final Transferable t) throws UnsupportedFlavorException, IOException, UnsupportedEncodingException, MalformedURLException, URISyntaxException {
        final InputStream is = (InputStream) t.getTransferData(DataFlavor.getTextPlainUnicodeFlavor());
        final BufferedReader in = new BufferedReader(new InputStreamReader(is, "UTF-16LE"));
        return new URI(in.readLine());
    }

    private BufferedImage getImageFromDnD(final Transferable t) throws IOException, UnsupportedFlavorException {
        return (BufferedImage) t.getTransferData(DataFlavor.imageFlavor);
    }
}


text:
package com.planet_ink.coffee_mud.Items.interfaces;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;

import java.util.Hashtable;
import java.util.Map;

import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

/**
 * An item that can be used to do damage to another mob.
 * That's what a weapon is.
 * They are classified by "damage type", which speaks generally
 * to the way the weapon hurts a mob, and a "weapon classification",
 * which speaks to the way in which the weapon is used, or the skills
 * required.
 * @author Bo Zimmerman
 */
public interface Weapon extends Item
{
	/** One of the weapon type, denotes natural weapon damage */
	public final static int TYPE_NATURAL=0;
	/** One of the weapon type, denotes slashing weapon damage */
	public final static int TYPE_SLASHING=1;
	/** One of the weapon type, denotes poking weapon damage */
	public final static int TYPE_PIERCING=2;
	/** One of the weapon type, denotes blunt weapon damage */
	public final static int TYPE_BASHING=3;
	/** One of the weapon type, denotes fire weapon damage */
	public final static int TYPE_BURNING=4;
	/** One of the weapon type, denotes explosive weapon damage */
	public final static int TYPE_BURSTING=5;
	/** One of the weapon type, denotes shooting weapon damage */
	public final static int TYPE_SHOOT=6;
	/** One of the weapon type, denotes cold weapon damage */
	public final static int TYPE_FROSTING=7;
	/** One of the weapon type, denotes poisony weapon damage */
	public final static int TYPE_GASSING=8;
	/** One of the weapon type, denotes acid weapon damage */
	public final static int TYPE_MELTING=9;
	/** One of the weapon type, denotes electric weapon damage */
	public final static int TYPE_STRIKING=10;
	/** One of the weapon type, denotes light weapon damage */
	public final static int TYPE_LASERING=11;
	/** One of the weapon type, denotes sonic weapon damage */
	public final static int TYPE_SONICING=12;
	/** One of the weapon type, denotes disrupting weapon damage */
	public final static int TYPE_DISRUPTING=13;
	/** One of the weapon type, denotes disrupting weapon damage */
	public final static int TYPE_STULTIFYING=14;
	/** One of the weapon type, denotes corrupting weapon damage */
	public final static int TYPE_CORRUPTING=15;
	/** One of the weapon type, denotes scraping weapon damage */
	public final static int TYPE_SCRAPING=16;

	/**
	 * Description code words for the weapon/damage types, indexed
	 * by the weapon/damage type values.
	 */
	public final static String[] TYPE_DESCS=
	{
		"NATURAL",
		"SLASHING",
		"PIERCING",
		"BASHING",
		"BURNING",
		"BURSTING",
		"SHOOTING",
		"FROSTING",
		"GASSING",
		"MELTING",
		"STRIKING",
		"LASERING",
		"SONICING",
		"DISRUPTING",
		"STULTIFYING",
		"CORRUPTING",
		"SCRAPING"
	};

	/**
	 * Map of damage types to CMMsg msg types
	 */
	public final static SHashtable<Integer,Integer> TYPE_MSG_MAP = new SHashtable<Integer,Integer>(new Integer[][]
	{
		{Integer.valueOf(TYPE_NATURAL), Integer.valueOf(-1)},
		{Integer.valueOf(TYPE_SLASHING), Integer.valueOf(-1)},
		{Integer.valueOf(TYPE_PIERCING), Integer.valueOf(-1)},
		{Integer.valueOf(TYPE_BASHING), Integer.valueOf(-1)},
		{Integer.valueOf(TYPE_BURNING), Integer.valueOf(CMMsg.TYP_FIRE)},
		{Integer.valueOf(TYPE_BURSTING), Integer.valueOf(-1)},
		{Integer.valueOf(TYPE_SHOOT), Integer.valueOf(-1)},
		{Integer.valueOf(TYPE_FROSTING), Integer.valueOf(CMMsg.TYP_COLD)},
		{Integer.valueOf(TYPE_GASSING), Integer.valueOf(CMMsg.TYP_GAS)},
		{Integer.valueOf(TYPE_MELTING), Integer.valueOf(CMMsg.TYP_ACID)},
		{Integer.valueOf(TYPE_STRIKING), Integer.valueOf(CMMsg.TYP_ELECTRIC)},
		{Integer.valueOf(TYPE_LASERING), Integer.valueOf(CMMsg.TYP_LASER)},
		{Integer.valueOf(TYPE_SONICING), Integer.valueOf(CMMsg.TYP_SONIC)},
		{Integer.valueOf(TYPE_DISRUPTING), Integer.valueOf(CMMsg.TYP_POISON)},
		{Integer.valueOf(TYPE_STULTIFYING), Integer.valueOf(CMMsg.TYP_PARALYZE)},
		{Integer.valueOf(TYPE_CORRUPTING), Integer.valueOf(CMMsg.TYP_UNDEAD)},
		{Integer.valueOf(TYPE_SCRAPING), Integer.valueOf(CMMsg.TYP_WATER)}
	});

	/**
	 * Map of CMMsg message types to damage types
	 */
	public final static SHashtable<Integer,Integer> MSG_TYPE_MAP = new SHashtable<Integer,Integer>(TYPE_MSG_MAP,true);

	/** One of the weapon classification, denotes an axe swinging type weapon */
	public final static int CLASS_AXE=0;
	/** One of the weapon classification, denotes a blunt type weapon */
	public final static int CLASS_BLUNT=1;
	/** One of the weapon classification, denotes an edged type weapon */
	public final static int CLASS_EDGED=2;
	/** One of the weapon classification, denotes a flailed type weapon */
	public final static int CLASS_FLAILED=3;
	/** One of the weapon classification, denotes a hammer swinging type weapon */
	public final static int CLASS_HAMMER=4;
	/** One of the weapon classification, denotes a natural type weapon */
	public final static int CLASS_NATURAL=5;
	/** One of the weapon classification, denotes a polearm type weapon */
	public final static int CLASS_POLEARM=6;
	/** One of the weapon classification, denotes a ranged type weapon */
	public final static int CLASS_RANGED=7;
	/** One of the weapon classification, denotes a sword type weapon */
	public final static int CLASS_SWORD=8;
	/** One of the weapon classification, denotes a dagger type weapon */
	public final static int CLASS_DAGGER=9;
	/** One of the weapon classification, denotes a staff type weapon */
	public final static int CLASS_STAFF=10;
	/** One of the weapon classification, denotes a thrown type weapon */
	public final static int CLASS_THROWN=11;

	/**
	 * Description code words for the weapon classifications, indexed
	 * by the weapon classification code values.
	 */
	public final static String[] CLASS_DESCS=
	{
		"AXE",
		"BLUNT",
		"EDGED",
		"FLAILED",
		"HAMMER",
		"KARATE",
		"POLEARM",
		"RANGED",
		"SWORD",
		"DAGGER",
		"STAFF",
		"THROWN"
	};

	/**
	 * Gets the type of damage this weapon does, from the weapon damage
	 * type list of codes.
	 * @see Weapon#TYPE_DESCS
	 * @return get weapon damage type code
	 */
	public int weaponDamageType();

	/**
	 * Sets the type of damage this weapon does, from the weapon damage
	 * type list of codes.
	 * @see Weapon#TYPE_DESCS
	 * @param newType get weapon damage type code
	 */
	public void setWeaponDamageType(int newType);

	/**
	 * Gets the general classification of this weapon, denoting how the
	 * weapon is used and the skills required.  The code comes from the
	 * weapon class list of codes.
	 * @see Weapon#CLASS_DESCS
	 * @return the weapon classification code
	 */
	public int weaponClassification();

	/**
	 * Sets the general classification of this weapon, denoting how the
	 * weapon is used and the skills required.  The code comes from the
	 * weapon class list of codes.
	 * @see Weapon#CLASS_DESCS
	 * @param newClassification the weapon classification code
	 */
	public void setWeaponClassification(int newClassification);

	/**
	 * Sets the minimum and maximum range of this weapon.
	 * Combined with the size of the room, and who attacks first,
	 * this can set the distance between two combatants.
	 * @see Environmental#maxRange()
	 * @see Environmental#minRange()
	 * @param min the minimum range 0=melee
	 * @param max the maximum range 0=melee
	 */
	public void setRanges(int min, int max);

	/**
	 * Gets the raw minimum and maximum range of this weapon.
	 * The array returned is in format min/max;
	 *
	 * @see Weapon#setRanges(int, int)
	 * @see Environmental#maxRange()
	 * @see Environmental#minRange()
	 * @return the ranges as an array, min and then max
	 */
	public int[] getRanges();

	/**
	 * Gets the string that would be shown if someone gets a hit with
	 * this weapon.
	 * @see Weapon#missString()
	 * @param damageAmount the amount of damage done with this weapon
	 * @return the message string to show someone hit with this weapon
	 */
	public String hitString(int damageAmount);

	/**
	 * Gets the string that would be shown if someone misses with
	 * this weapon.
	 * @see Weapon#hitString(int)
	 * @return the message string to show someone misses with this weapon
	 */
	public String missString();
}


text:
layout: tag
section-type: tag
title: google_app_script
---
## Tag


text:
FROM centos6/base
MAINTAINER Nemanja Andrejevic <andrejevicnemanja@gmail.com>

# Install Nginx
ADD nginx.repo /etc/yum.repos.d/nginx.repo
RUN yum -y install nginx && \
yum clean all

# Configuring Nginx
RUN ln -sf /dev/stdout /var/log/nginx/access.log && \
ln -sf /dev/stderr /var/log/nginx/error.log

# Installing PHP
RUN yum-config-manager --add-repo http://rpms.famillecollet.com/enterprise/remi.repo && \
yum -y --enablerepo=remi-php56 --enablerepo=remi install php-fpm php-mbstring php-imap php-soap gd-last php-gd ImageMagick php-xml php-mysqlnd php-process php-cli php-pear php-bcmath php-mcrypt php-intl && \
yum clean all && \
chown root:nginx -R /var/lib/php/session && \
chown root:nginx -R /var/lib/php/wsdlcache

# Configuring PHP FPM
RUN echo 'cgi.fix_pathinfo = 0;' >> /etc/php.ini && sed -i "s/;date.timezone =.*/date.timezone = UTC/" /etc/php.ini
ADD www.conf /etc/php-fpm.d/www.conf

# Add Composer
RUN curl -sS https://getcomposer.org/installer | php && mv composer.phar /usr/local/bin/composer && chmod +x /usr/local/bin/composer

# Exposing ports
EXPOSE 80 9000

# Configuring supervisor
ADD supervisord.conf /etc/supervisord.conf

# Setting up docker entrypoint
ADD entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]

CMD ["supervisord", "-n"]


text:
/**
 * Created by bert on 07.07.16.
 */

import * as reob from "./serverModule"
import * as wm from "web-methods"
import * as expressModule from "express"
import * as http from "http"
import * as path from "path"
import * as mongo from "mongodb"
import * as fs from "fs"
import * as compression from "compression"
import {MongoClient} from "mongodb";

export declare type LoadingCheck = (id:string, request:reob.Request, obj:any ) => boolean|Promise<void>;
export declare type ServiceProvider = (s:reob.Request) => Object

export interface MethodEventListener {
    ( object:any, functionName:string, args:any[], request:reob.Request, result?:any ) : Promise<void>|void
}

export class Server{

    private collections:{ [index:string]:reob.Collection<any> } = {};
    private collectionLoadingEnabled:{ [index:string]:boolean|LoadingCheck  } = {};
    private services:{ [index:string]: Object|ServiceProvider } = {};
    private webMethods:wm.WebMethods;
    private serializer:reob.Serializer;
    private beforeMethodListener:Array<MethodEventListener> = [];
    private afterMethodListener:Array<MethodEventListener> = [];
    private express:expressModule.Application;
    private httpServer:any;
    private webRootPath: string;
    private indexFileName: string;
    private mongoDb:mongo.Db;
    private mongoUrl:string;
    private port:number;

    private requestFactory : (ud:any)=>reob.Request;

    private webMethodsAdded:Array<string> = [];

    constructor( theMongoDbOrDbUrl:any ) {
        this.webMethods = new wm.WebMethods();
        this.serializer = new reob.Serializer();
        this.express = expressModule();
        this.express.use(compression());
        this.httpServer = http.createServer(this.express);

        if( typeof theMongoDbOrDbUrl=="string" ) {
            this.mongoUrl = <string>theMongoDbOrDbUrl;
        }else{
            this.mongoDb = <mongo.Db>theMongoDbOrDbUrl;
        }
    }

    getWebRootPath():string{
        return this.webRootPath;
    }

    stop(){
        this.httpServer.close();
    }

    async connectToMongoDb():Promise<void>{
        if( !this.mongoDb ) {
            //let client = new MongoClient(this.mongoUrl);
            let client:MongoClient = await MongoClient.connect(this.mongoUrl);
            this.mongoDb = client.db();
        }
        for (var i in this.collections) {
            var c: reob.Collection<any> = this.collections[i];
            c.setMongoCollection(this.mongoDb);
        }
    }

    async start( port?:number ):Promise<void>{
        this.webMethods.registerEndpoint(this.express);
        this.addAllEntityWebMethods();
        this.registerGetter();
        if( this.webRootPath ){
            this.registerStaticGET();
        }
        this.port = port || 8080;
        await this.connectToMongoDb();
        await new Promise<void>((resolve, reject)=> {
            this.httpServer.listen(this.port, () => {
                resolve();
            });
        });
    }

    getExpress():expressModule.Application{
        return this.express;
    }

    serveStatic( theWebRootPath:string, indexFileName?:string ) {

        this.webRootPath = path.resolve( theWebRootPath );
        this.indexFileName = indexFileName ? indexFileName : "index.html";
    }

    private registerStaticGET(){
        if( this.webRootPath && this.indexFileName ) {
            this.express.get('/*', (req:any, res:any, next:Function) => {

                //This is the current file they have requested
                var file = req.params[0];
                // if( file.indexOf( "js/")!=0 && file.indexOf( "css/")!=0 && file.indexOf( "fonts/")!=0  && file.indexOf( "img/" )!=0 && file.indexOf( "src/")!=0 &&file.indexOf( "components/")!=0 &&file.indexOf( "bootstrap/")!=0 && file.indexOf( "bundle")!=0 )
                //     file = indexFileName;

                var fileName = path.resolve(this.webRootPath, file);
                fs.exists(fileName, (exists:boolean) => {
                    if (!exists)
                        fileName = path.resolve(this.webRootPath, this.indexFileName);
                    res.sendFile(fileName);
                });
            });

            this.express.get('/', (req:any, res:any, next:Function) => {
                var fileName = path.resolve(this.webRootPath, this.indexFileName);
                res.sendFile(fileName);
            });
        }
    }

    addCollection( c: reob.Collection<any> ):void{
        this.collections[c.getName()] = c;
        if( this.mongoDb )
            c.setMongoCollection(this.mongoDb);
    }

    setLoadingAllowed(c:reob.Collection<any>, i:boolean|LoadingCheck ) {
        this.collectionLoadingEnabled[c.getName()] = i;
    }

    addService( serviceName, service:Object|ServiceProvider ):void{
        // singletons dont need a
        var o;
        if( typeof service=="object" ) {
            reob.SerializationPath.setObjectContext(service, undefined, <reob.Handler>this, undefined);
            o = service;
        }else{
            o = (<Function>service)({});
        }
        var serviceClass = reob.getClass(o);
        // var serviceName = omm.getServiceName(serviceClass);
        // if( !serviceName )
        //     throw new Error("Added service has no @Service decorator. Class name:"+ omm.getClassName(o) );
        this.services[serviceName] = service;

        var serviceClass = reob.getClass(o);
        reob.getRemoteFunctionNames(serviceClass).forEach((remoteFunctionName:string)=>{
            var options = reob.getMethodOptions(serviceClass,remoteFunctionName);
            if( !options.name ) {
                options.name = serviceName + "." + options.propertyName;
            }
            this.addWebMethod( options );
        });
    }

    private notifyBeforeMethodListeners( object:any, functionName:string, args:any[], request:reob.Request ):Promise<void>{
        var promises = [];
        this.beforeMethodListener.forEach((ml:MethodEventListener)=>{
            promises.push( reob.EventListenerRegistry.castToPromise( ()=>{ ml(object, functionName, args, request); } ) );

        });
        return Promise.all( promises ).then(()=>{ });
    }

    private notifyAfterMethodListeners( object:any, functionName:string, args:any[], request:reob.Request, result:any ):Promise<void>{
        var promises = [];
        this.afterMethodListener.forEach((ml:MethodEventListener)=>{
            promises.push( reob.EventListenerRegistry.castToPromise( ()=>{ ml(object, functionName, args, request, result) } ) );
        });
        return Promise.all( promises ).then(()=>{ });
    }

    onBeforeMethod( eventHandler:MethodEventListener ){
        this.beforeMethodListener.push(eventHandler);
    }
    onAfterMethod( eventHandler:MethodEventListener ){
        this.afterMethodListener.push(eventHandler);
    }

    removeAllMethodListeners(){
        this.beforeMethodListener = [];
        this.afterMethodListener = [];
    }

    private addAllEntityWebMethods():void {
        reob.getEntityClasses().forEach((c:reob.TypeClass<any>)=>{
            reob.getRemoteFunctionNames(c).forEach((remoteFunctionName:string)=>{
                var options = reob.getMethodOptions(c,remoteFunctionName);
                if( !options.name ){
                    options.name = reob.getClassName(c)+"."+options.propertyName;
                }
                this.addWebMethod(options);
            });
        });
    }

    getPort():number{
        return this.port;
    }

    setRequestFactory( f : (userData:any)=>reob.Request ){
        this.requestFactory = f;
    }

    protected createRequest( userData:any ):reob.Request{
        if( this.requestFactory ){
            return this.requestFactory( userData );
        } else {
            return {userData};
        }
    }

    private addWebMethod( options:reob.IMethodOptions ){
        if( this.webMethodsAdded.indexOf(options.name)!=-1 )
            return;
        this.webMethodsAdded.push(options.name);
        this.webMethods.add(options.name, (...args:any[])=>{
            var startTime = Date.now();

            // the object id is the first parameter
            var objectId = args.shift();

            // the user Data is the second parameter
            var userData = args.shift();
            var request:reob.Request = this.createRequest( userData );

            // convert parameters given to the web method from documents to objects
            this.convertWebMethodParameters(args, options.parameterTypes, userData);

                // load object based on the object id. this could either be a registered object or an object form a collection
            var objectPromise = this.retrieveObject(objectId, request).then((object:any)=> {
                // this might be the collection update or another function that is called directly
                return this.notifyBeforeMethodListeners( object, options.name.split(".")[1], args, request ).then(()=> {
                    return object;
                });
            });
            var resultPromise = objectPromise.then( (object:any) => {
                return object[options.propertyName].apply(object, args);
            });
            return Promise.all([objectPromise, resultPromise]).then((values:any[])=> { // convert the result to a document
                var object = values[0];
                var result = values[1];
                var res:any = {};
                if (result) {
                    res.document = this.serializer.toDocument(result, true, true);
                }
                return this.notifyAfterMethodListeners( object, options.name.split(".")[1], args, request, result ).then(()=> {
                    return res;
                });
            });
        });
    }

    private getCollection(objectId:string):reob.Collection<any>{
        var sPath = new reob.SerializationPath( objectId );
        var collectionName = sPath.getCollectionName();
        var collection:reob.Collection<Object> = collectionName ? this.collections[collectionName] : undefined;
        return collection;
    }

    private retrieveObject( objectId:string, request:reob.Request ):Promise<any>{
        var service = this.services[objectId];
        if( service ) {
            var s:any = service;
            if( typeof service == "function" ){
                s = (<ServiceProvider>service)(request);
            }
            return Promise.resolve(s);
        }
        else{
            if (typeof objectId != "string")
                throw new Error("Path needs to be a string");
            var sPath = new reob.SerializationPath( objectId );
            var collection = this.getCollection(objectId);
            if (collection) {
                return collection.getById(sPath.getId(), request).then((o)=>{
                    return sPath.getSubObject(o);
                });
            }
            else
                return Promise.reject( "No collection found to retrieve object. Key:" + objectId );
        }
    }

    private registerGetter(){
        this.webMethods.add("get", (collectionName:string, objectId:string, userData:any )=>{
            var request:reob.Request = this.createRequest( userData );
            var allowedPromise:Promise<void>;

            return new Promise<reob.Object>((resolve, reject)=>{
                if( collectionName )
                    resolve( this.retrieveObject(collectionName + "[" + objectId + "]", request) );
                else
                    reject( new Error("No collection name given") );
            }).then((object)=>{
                var i:any = this.collectionLoadingEnabled[collectionName];
                if( typeof i == "function" ){
                    return Promise.resolve( i( objectId, request, object ) ).then(()=>object);
                }else{
                    return Promise.resolve( i ).then(()=>object);
                }
            }).then((obj)=> {
                var doc = obj ? this.serializer.toDocument(obj, true, true) : undefined;
                return doc;
            });
        });
    }

    // converts parameters given to the web method from documents to objects
    private convertWebMethodParameters( args:Array<any>, classNames:Array<string>, request:reob.Request ){
        for (var i = 0; i < args.length; i++) {
            if (classNames && classNames.length > i) {
                var cls = reob.getEntityClassByName(classNames[i]);
                if (cls) {
                    if (typeof args[i] == "string")
                        args[i] = this.retrieveObject(args[i], request);
                    else if (typeof args[i] == "object")
                        args[i] = this.serializer.toObject(args[i], cls);
                }
            }
        }
    }

}


text:
package eu.socialsensor.framework.abstractions.socialmedia.instagram;

import org.jinstagram.entity.common.User;
import org.jinstagram.entity.users.basicinfo.Counts;
import org.jinstagram.entity.users.basicinfo.UserInfoData;

import eu.socialsensor.framework.common.domain.SocialNetworkSource;
import eu.socialsensor.framework.common.domain.StreamUser;

/**
 * Class that holds the information of an instagram user
 * @author ailiakop
 * @email  ailiakop@iti.gr
 */
public class InstagramStreamUser extends StreamUser {

	/**
	 *
	 */
	private static final long serialVersionUID = -186352302816765493L;

	public InstagramStreamUser(User user) {
		super(SocialNetworkSource.Instagram.toString(), Operation.NEW);
		if (user == null) return;

		//Id
		id = SocialNetworkSource.Instagram + "#" + user.getId();
		//The id of the user in the network
		Long userLId = user.getId();
		userid = userLId.toString();
		//The name of the user
		name = user.getFullName();
		//The username of the user
		username = user.getUserName();
		//streamId
		streamId = SocialNetworkSource.Instagram.toString();
		//The description of the user
		description = user.getBio();
		//Profile picture of the user
		profileImage = user.getProfilePictureUrl();
		//The link to the user's profile
		linkToProfile = user.getWebsiteUrl();
		//The link to the user's profile
		pageUrl = "http://instagram.com/" + username;
	}

	public InstagramStreamUser(UserInfoData user) {
		super(SocialNetworkSource.Instagram.toString(), Operation.NEW);
		if (user == null) return;

		//Id
		id = SocialNetworkSource.Instagram + "#" + user.getId();
		//The id of the user in the network
		Long userLId = user.getId();
		userid = userLId.toString();
		//The name of the user
		name = user.getFullName();
		//The username of the user
		username = user.getUsername();
		//streamId
		streamId = SocialNetworkSource.Instagram.toString();
		//The description of the user
		description = user.getBio();
		//Profile picture of the user
		profileImage = user.getProfile_picture();
		//The link to the user's profile
		pageUrl = "http://instagram.com/" + username;

		Counts counts = user.getCounts();
		if(counts != null) {
			items = counts.getMedia();
			friends = (long) counts.getFollows();
			followers = (long) counts.getFollwed_by();
		}

	}
}


text:
<?php

namespace Qandidate;

interface GameStorage
{
    public function save(Api $game);
    public function find($uuid);
    public function findAll();
}


text:
/**
 *
 */
package org.sjitech.myassist.core.db;

import java.net.InetAddress;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

import org.sjitech.myassist.core.ApplicationException;
import org.sjitech.myassist.core.db.config.ConfigConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * database driver inspect manager class. it can be get database meta info by
 * jdbc api or by database system tables/views
 *
 * @author sji_zhang_x
 *
 */
public class DriverInspectManager {

	/**
	 * log handler
	 */
	static Logger log = LoggerFactory.getLogger(DriverInspectManager.class);

	/**
	 * get connection inspect instance by the configured name
	 *
	 * @param type
	 * @param name
	 * @return
	 */
	public static ConnectionInspect getConnectionInspect(ConfigConnection config) {
		if (log.isDebugEnabled()) {
			log.debug("connect to " + config.getDbType() + ". url=" + config.getUrl());
		}

		try {
			Class.forName(config.getDriverClass());

			Properties props = new Properties();
			if (config.getConnectProperties() != null) {
				props.putAll(config.getConnectProperties());
			}
			props.put("user", config.getUser());
			props.put("password", config.getPasswd());

			Connection conn = DriverManager.getConnection(config.getUrl(),
					props);

			// set the client info
			String osUserName = System.getProperty("user.name");
			String clientHostName = InetAddress.getLocalHost().getHostName();
			conn.setClientInfo("ApplicationName", "myassist");
			conn.setClientInfo("ClientUser", osUserName);
			conn.setClientInfo("ClientHostname", clientHostName);

			if (log.isDebugEnabled()) {
				log.debug("ClientUser=" + osUserName);
				log.debug("ClientHostname=" + clientHostName);
			}

			return config.getDbType().getInspectClass().
					getConstructor(Connection.class).newInstance(conn);
		} catch (Exception e) {
			throw new ApplicationException(e);
		}
	}
}


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="keywords" content="彩生活">
    <meta name="description" content="彩生活">
    <title>{% block title %}{% endblock %}</title>
    <link href="/static/css/bootstrap.min.css" rel="stylesheet">
    <link href="/static/css/register.css" rel="stylesheet">
    {% block css %}{% endblock %}

    {% block body %}

{% block content_title %}{% endblock %}

            {% block content %}{% endblock %}

    {% endblock %}

© 2013 SFI Suzhou Company, Inc.

{% block script %}{% endblock %}


text:
package tutorial.core.repositories.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import tutorial.core.models.entities.BlogEntry;
import tutorial.core.models.entities.RoomGroup;
import tutorial.core.repositories.RoomGroupRepo;

@Repository
public class JpaRoomGroupRepo implements RoomGroupRepo {
	@PersistenceContext
    private EntityManager em;

	@Override
	public RoomGroup createRoomGroup(RoomGroup data) {
        em.persist(data);
        return data;
    }

	@Override
	public RoomGroup updateRoomGroup(Long roomGroupId, RoomGroup roomGroupData) {
		RoomGroup entry = em.find(RoomGroup.class, roomGroupId);
        entry.setRoomGroupName(roomGroupData.getRoomGroupName());
        return entry;
	}

    @Override
    public RoomGroup deleteRoomGroup(Long id) {
    	RoomGroup entry = em.find(RoomGroup.class, id);
        em.remove(entry);
        return entry;
    }

	@Override
	public List<RoomGroup> findAllRoomGroups() {
        Query query = em.createQuery("SELECT b from RoomGroup b");
        return query.getResultList();
    }

	@Override
	public RoomGroup findRoomGroup(Long roomGroupId) {
        return em.find(RoomGroup.class, roomGroupId);
    }

	@Override
	public RoomGroup findRoomGroupByTitle(String roomGroupName) {
        Query query = em.createQuery("SELECT b from RoomGroup b where b.roomGroupName=?1");
        query.setParameter(1, roomGroupName);
        List<RoomGroup> roomGroups = query.getResultList();
        if(roomGroups.isEmpty()) {
            return null;
        } else {
            return roomGroups.get(0);
        }
    }

}


text:
                                     SYSCTL_FMULT_NONE | SYSCTL_SYSDIV(2) |   \
                                     SYSCTL_PLL_ENABLE)

//
// 200MHz SYSCLK frequency based on the above DEVICE_SETCLOCK_CFG. Update the
// code below if a different clock configuration is used!
//
#define DEVICE_SYSCLK_FREQ          ((DEVICE_OSCSRC_FREQ * 40 * 1) / 2)

//
// ControlCARD Configuration
//
#else

//
// 20MHz XTAL on controlCARD. For use with SysCtl_getClock().
//
#define DEVICE_OSCSRC_FREQ          20000000U

//
// Define to pass to SysCtl_setClock(). Will configure the clock as follows:
// PLLSYSCLK = 20MHz (XTAL_OSC) * 20 (IMULT) * 1 (FMULT) / 2 (PLLCLK_BY_2)
//
#define DEVICE_SETCLOCK_CFG         (SYSCTL_OSCSRC_XTAL | SYSCTL_IMULT(20) |  \
                                     SYSCTL_FMULT_NONE | SYSCTL_SYSDIV(2) |   \
                                     SYSCTL_PLL_ENABLE)

//
// 200MHz SYSCLK frequency based on the above DEVICE_SETCLOCK_CFG. Update the
// code below if a different clock configuration is used!
//
#define DEVICE_SYSCLK_FREQ          ((DEVICE_OSCSRC_FREQ * 20 * 1) / 2)

#endif

//
// 50MHz LSPCLK frequency based on the above DEVICE_SYSCLK_FREQ and a default
// low speed peripheral clock divider of 4. Update the code below if a
// different LSPCLK divider is used!
//
#define DEVICE_LSPCLK_FREQ          (DEVICE_SYSCLK_FREQ / 4)

//*****************************************************************************
//
// Macro to call SysCtl_delay() to achieve a delay in microseconds. The macro
// will convert the desired delay in microseconds to the count value expected
// by the function. \b x is the number of microseconds to delay.
//
//*****************************************************************************
#define DEVICE_DELAY_US(x) SysCtl_delay(((((long double)(x)) / (1000000.0L /  \
                              (long double)DEVICE_SYSCLK_FREQ)) - 9.0L) / 5.0L)

//*****************************************************************************
//
// Defines, Globals, and Header Includes related to Flash Support
//
//*****************************************************************************
#ifdef _FLASH
#include <stddef.h>

extern uint16_t RamfuncsLoadStart;
extern uint16_t RamfuncsLoadEnd;
extern uint16_t RamfuncsLoadSize;
extern uint16_t RamfuncsRunStart;
extern uint16_t RamfuncsRunEnd;
extern uint16_t RamfuncsRunSize;

#define DEVICE_FLASH_WAITSTATES 3

#endif

//*****************************************************************************
//
// Function Prototypes
//
//*****************************************************************************
extern void Device_init(void);
extern void Device_enableAllPeripherals(void);
extern void Device_initGPIO(void);
extern void Device_enableUnbondedGPIOPullupsFor176Pin(void);
extern void Device_enableUnbondedGPIOPullupsFor100Pin(void);
extern void Device_enableUnbondedGPIOPullups(void);
extern void __error__(char *filename, uint32_t line);

//
// End of file
//


text:
using System;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
using MatterHackers.Agg.Platform;
using MatterHackers.RenderOpenGl;

#if USE_GLES
using OpenTK.Graphics.ES11;
#else

using OpenTK.Graphics.OpenGL;

#endif

namespace MatterHackers.Agg.UI
{
	public class OpenGLSystemWindow : WinformsSystemWindow
	{
		private AggGLControl glControl;

		public OpenGLSystemWindow()
		{
			// Set GraphicsMode via user overridable settings
			var config = AggContext.Config.GraphicsMode;

			// NOTE: OpenTK3 will run in Windows Sandbox (no proper GL driver), but OpenTK4 won't, it seems.

#if USE_OPENTK4
			var graphicsMode = new OpenTK.WinForms.GLControlSettings {
				Profile = OpenTK.Windowing.Common.ContextProfile.Compatability,
#if DEBUG
				Flags = OpenTK.Windowing.Common.ContextFlags.Debug,
#endif
				NumberOfSamples = config.FSAASamples,
				IsEventDriven = true,
			};
#else
			var graphicsMode = new OpenTK.Graphics.GraphicsMode(config.Color, config.Depth, config.Stencil, config.FSAASamples);

			// If the GPU driver is disabled in Windows, this could be used to test context creation failure.
			//var graphicsMode = new OpenTK.Graphics.GraphicsMode(config.Color, config.Depth, config.Stencil, config.FSAASamples + 100, OpenTK.Graphics.ColorFormat.Empty, 100, true);
#endif

			glControl = new AggGLControl(graphicsMode)
			{
				Dock = DockStyle.Fill,
				Location = new Point(0, 0),
				TabIndex = 0,
#if !USE_OPENTK4
				VSync = false,
#endif
			};

			// TODO: Disable VSync when using OpenTK 4? Current versions on NuGet do not expose VSync.
#if !USE_OPENTK4
			//(glControl.Context as OpenTK.Windowing.Desktop.GLFWGraphicsContext).SwapInterval = 0;
#endif

			RenderOpenGl.OpenGl.GL.Instance = new OpenTkGl();

			this.Controls.Add(glControl);
		}

		private bool doneLoading = false;

		protected override void OnClosed(EventArgs e)
		{
			if (!this.IsDisposed
				|| !glControl.IsDisposed)
			{
				glControl.MakeCurrent();
				glControl.releaseAllGlData.Release();
			}

			base.OnClosed(e);
		}

		protected override void OnLoad(EventArgs e)
		{
			id = count++;

			base.OnLoad(e);

			doneLoading = true;

			this.EventSink = new WinformsEventSink(glControl, AggSystemWindow);

			// Init();
			if (!AggSystemWindow.Resizable)
			{
				this.FormBorderStyle = FormBorderStyle.FixedDialog;
				this.MaximizeBox = false;
			}

			// Change the WindowsForms window to match the target SystemWindow bounds
			this.ClientSize = new Size((int)AggSystemWindow.Width, (int)AggSystemWindow.Height);

			// Restore to the last maximized or normal window state
			this.WindowState = AggSystemWindow.Maximized ? FormWindowState.Maximized : FormWindowState.Normal;

			this.IsInitialized = true;
			initHasBeenCalled = true;
		}

#if USE_OPENTK4
		// HACK: Huh!? Makes keyboard input work. https://github.com/opentk/GLControl/issues/18
		protected override void OnShown(EventArgs e)
		{
			base.OnShown(e);
			glControl.Focus();
		}
#endif

		private void SetupViewport()
		{
			// If this throws an assert, you are calling MakeCurrent() before the glControl is done being constructed.
			// Call this function you have called Show().
			glControl.MakeCurrent();
			int w = glControl.Width;
			int h = glControl.Height;
#if USE_GLES
            GL.MatrixMode(All.Projection);
#else
			GL.MatrixMode(MatrixMode.Projection);
#endif
			GL.LoadIdentity();
			GL.Ortho(0, w, 0, h, -1, 1); // Bottom-left corner pixel has coordinate (0, 0)
			GL.Viewport(0, 0, w, h); // Use all of the glControl painting area
		}

		protected override void OnPaint(PaintEventArgs paintEventArgs)
		{
			if (Focused)
			{
				glControl.Focus();
			}

			// We have to make current the gl for the window we are.
			// If this throws an assert, you are calling MakeCurrent() before the glControl is done being constructed.
			// Call this function after you have called Show().
			glControl.MakeCurrent();

			if (CheckGlControl())
			{
				base.OnPaint(paintEventArgs);
			}

			CheckGlControl();
		}

		protected override void OnResize(EventArgs e)
		{
			Rectangle bounds = new Rectangle(0, 0, ClientSize.Width, ClientSize.Height);

			// Suppress resize events on the Windows platform when the form is being minimized and/or when a Resize event has fired
			// but the control dimensions remain the same. This prevents a bounds resize from the current dimensions to 0,0 and a
			// subsequent resize on Restore to the origin dimensions. In addition, this guard prevents the loss of control state
			// due to cascading control regeneration and avoids the associated performance hit and visible rendering lag during Restore
			if (doneLoading && this.WindowState != FormWindowState.Minimized && glControl.Bounds != bounds)
			{
				// If this throws an assert, you are calling MakeCurrent() before the glControl is done being constructed.
				// Call this function you have called Show().
				glControl.MakeCurrent();
				Invalidate();
				// glSurface.Location = new Point(0, 0);
				glControl.Bounds = bounds;

				if (initHasBeenCalled)
				{
					CheckGlControl();
					SetAndClearViewPort();
					base.OnResize(e);
					CheckGlControl();
				}
				else
				{
					base.OnResize(e);
				}

				SetupViewport();
			}
		}

		public override void CopyBackBufferToScreen(Graphics displayGraphics)
		{
			// If this throws an assert, you are calling MakeCurrent() before the glControl is done being constructed.
			// Call this function you have called Show().
			glControl.SwapBuffers();
		}

		private static int count;
		private int id;

		public override string ToString()
		{
			return id.ToString();
		}

		private bool viewPortHasBeenSet = false;

		private void SetAndClearViewPort()
		{
			GL.Viewport(0, 0, this.ClientSize.Width, this.ClientSize.Height);                   // Reset The Current Viewport
			viewPortHasBeenSet = true;

			// The following lines set the screen up for a perspective view. Meaning things in the distance get smaller.
			// This creates a realistic looking scene.
			// The perspective is calculated with a 45 degree viewing angle based on the windows width and height.
			// The 0.1f, 100.0f is the starting point and ending point for how deep we can draw into the screen.

			GL.MatrixMode(MatrixMode.Projection);
			GL.LoadIdentity();

			GL.MatrixMode(MatrixMode.Modelview);
			GL.LoadIdentity();
			GL.Scissor(0, 0, this.ClientSize.Width, this.ClientSize.Height);

			NewGraphics2D().Clear(new ColorF(1, 1, 1, 1));
		}

		private bool CheckGlControl()
		{
			if (firstGlControlSeen == null)
			{
				firstGlControlSeen = AggGLControl.currentControl;
			}

			// if (firstGlControlSeen != MyGLControl.currentControl)
			if (AggGLControl.currentControl.Id != this.id)
			{
				Debug.WriteLine("Is {0} Should be {1}".FormatWith(firstGlControlSeen.Id, AggGLControl.currentControl.Id));
				// throw new Exception("We have the wrong gl control realized.");
				return false;
			}

			return true;
		}

		private AggGLControl firstGlControlSeen = null;

		public override Graphics2D NewGraphics2D()
		{
			if (!viewPortHasBeenSet)
			{
				SetAndClearViewPort();
			}

			Graphics2D graphics2D = new Graphics2DOpenGL(this.ClientSize.Width, this.ClientSize.Height, GuiWidget.DeviceScale);
			graphics2D.PushTransform();

			return graphics2D;
		}

		private bool initHasBeenCalled = false;

		private Keys modifierKeys = Keys.None;
		private bool modifiersOverridden = false;

		internal void SetModifierKeys(Keys modifiers)
		{
			modifierKeys = modifiers;
			modifiersOverridden = true;
		}

		public override Keys ModifierKeys
		{
			get {
				if (modifiersOverridden)
				{
					return modifierKeys;
				}
				return base.ModifierKeys;
			}
		}
	}
}


text:
package org.springframework.vault.authentication;

import java.net.URI;
import java.util.Arrays;
import java.util.UUID;

import org.springframework.lang.Nullable;
import org.springframework.util.Assert;

/**
 * Authentication options for {@link AwsEc2Authentication}.
 * <p>
 * Authentication options provide the path, the Identity Document URI and an optional
 * role. {@link AwsEc2AuthenticationOptions} can be constructed using {@link #builder()}.
 * Instances of this class are immutable once constructed.
 *
 * @author Mark Paluch
 * @see AwsEc2Authentication
 * @see #builder()
 */
public class AwsEc2AuthenticationOptions {

	public static final URI DEFAULT_PKCS7_IDENTITY_DOCUMENT_URI = URI
			.create("http://169.254.169.254/latest/dynamic/instance-identity/pkcs7");

	public static final String DEFAULT_AWS_AUTHENTICATION_PATH = "aws-ec2";

	/**
	 * Default {@link AwsEc2AuthenticationOptions} using
	 * {@link #DEFAULT_AWS_AUTHENTICATION_PATH} and
	 * {@link #DEFAULT_PKCS7_IDENTITY_DOCUMENT_URI}.
	 */
	public static final AwsEc2AuthenticationOptions DEFAULT = new AwsEc2AuthenticationOptions();

	/**
	 * Path of the aws-ec2 authentication backend mount.
	 */
	private final String path;

	/**
	 * {@link URI} to the AWS EC2 PKCS#7-signed identity document.
	 */
	private final URI identityDocumentUri;

	/**
	 * EC2 instance role name. May be {@literal null} if none.
	 */
	@Nullable
	private final String role;

	/**
	 * Authentication nonce.
	 */
	private final Nonce nonce;

	private AwsEc2AuthenticationOptions() {
		this(DEFAULT_AWS_AUTHENTICATION_PATH, DEFAULT_PKCS7_IDENTITY_DOCUMENT_URI, "",
				Nonce.generated());
	}

	private AwsEc2AuthenticationOptions(String path, URI identityDocumentUri,
			@Nullable String role, Nonce nonce) {

		this.path = path;
		this.identityDocumentUri = identityDocumentUri;
		this.role = role;
		this.nonce = nonce;
	}

	/**
	 * @return a new {@link AwsEc2AuthenticationOptionsBuilder}.
	 */
	public static AwsEc2AuthenticationOptionsBuilder builder() {
		return new AwsEc2AuthenticationOptionsBuilder();
	}

	/**
	 * @return the path of the aws-ec2 authentication backend mount.
	 */
	public String getPath() {
		return path;
	}

	/**
	 * @return the {@link URI} to the AWS EC2 PKCS#7-signed identity document.
	 */
	public URI getIdentityDocumentUri() {
		return identityDocumentUri;
	}

	/**
	 * @return the role, may be {@literal null} if none.
	 */
	@Nullable
	public String getRole() {
		return role;
	}

	/**
	 * @return the configured {@link Nonce}.
	 */
	public Nonce getNonce() {
		return nonce;
	}

	/**
	 * Builder for {@link AwsEc2AuthenticationOptionsBuilder}.
	 */
	public static class AwsEc2AuthenticationOptionsBuilder {

		private String path = DEFAULT_AWS_AUTHENTICATION_PATH;
		private URI identityDocumentUri = DEFAULT_PKCS7_IDENTITY_DOCUMENT_URI;

		@Nullable
		private String role;

		private Nonce nonce = Nonce.generated();

		AwsEc2AuthenticationOptionsBuilder() {
		}

		/**
		 * Configure the mount path.
		 *
		 * @param path must not be empty or {@literal null}.
		 * @return {@code this} {@link AwsEc2AuthenticationOptionsBuilder}.
		 */
		public AwsEc2AuthenticationOptionsBuilder path(String path) {

			Assert.hasText(path, "Path must not be empty");

			this.path = path;
			return this;
		}

		/**
		 * Configure the Identity Document {@link URI}.
		 *
		 * @param identityDocumentUri must not be {@literal null}.
		 * @return {@code this} {@link AwsEc2AuthenticationOptionsBuilder}.
		 * @see #DEFAULT_PKCS7_IDENTITY_DOCUMENT_URI
		 */
		public AwsEc2AuthenticationOptionsBuilder identityDocumentUri(
				URI identityDocumentUri) {

			Assert.notNull(identityDocumentUri, "Identity document URI must not be null");

			this.identityDocumentUri = identityDocumentUri;
			return this;
		}

		/**
		 * Configure the name of the role against which the login is being attempted.If
		 * role is not specified, then the login endpoint looks for a role bearing the
		 * name of the AMI ID of the EC2 instance that is trying to login.
		 *
		 * @param role may be empty or {@literal null}.
		 * @return {@code this} {@link AwsEc2AuthenticationOptionsBuilder}.
		 */
		public AwsEc2AuthenticationOptionsBuilder role(@Nullable String role) {

			this.role = role;
			return this;
		}

		/**
		 * Configure a {@link Nonce} for login requests. Defaults to
		 * {@link Nonce#generated()}.
		 *
		 * @param nonce must not be {@literal null}.
		 * @return {@code this} {@link AwsEc2AuthenticationOptionsBuilder}.
		 * @since 1.1
		 */
		public AwsEc2AuthenticationOptionsBuilder nonce(Nonce nonce) {

			Assert.notNull(nonce, "Nonce must not be null");

			this.nonce = nonce;
			return this;
		}

		/**
		 * Build a new {@link AwsEc2AuthenticationOptions} instance.
		 *
		 * @return a new {@link AwsEc2AuthenticationOptions}.
		 */
		public AwsEc2AuthenticationOptions build() {

			Assert.notNull(identityDocumentUri, "IdentityDocumentUri must not be null");

			return new AwsEc2AuthenticationOptions(path, identityDocumentUri, role,
					nonce);
		}
	}

	/**
	 * Value object for an authentication nonce.
	 *
	 * @since 1.1
	 */
	public static class Nonce {

		private final char[] value;

		protected Nonce(char[] value) {
			this.value = value;
		}

		/**
		 * Create a new generated {@link Nonce} using {@link UUID}.
		 *
		 * @return a new generated {@link Nonce} using {@link UUID}.
		 */
		public static Nonce generated() {
			return new Generated();
		}

		/**
		 * Create a wrapped {@link Nonce} given a {@code nonce} value.
		 *
		 * @return a wrapped {@link Nonce} given for the {@code nonce} value.
		 */
		public static Nonce provided(char[] nonce) {

			Assert.notNull(nonce, "Nonce must not be null");

			return new Provided(Arrays.copyOf(nonce, nonce.length));
		}

		/**
		 * @return the nonce value.
		 */
		public char[] getValue() {
			return value;
		}

		static class Generated extends Nonce {

			Generated() {
				super(UUID.randomUUID().toString().toCharArray());
			}
		}

		static class Provided extends Nonce {

			Provided(char[] nonce) {
				super(nonce);
			}
		}
	}
}


text:
using System;
using System.Runtime.CompilerServices;

namespace Test
{

    public class C1<T>
    {

        public static string GetString()
        {
            return "foo";
        }
    }

    public class C1Helper
    {
        public static bool IsFoo(string val)
        {
            return ((object)"foo" == (object)val);
        }
    }

}


text:
using BadMishka.DocumentFormat.LuceneIndex.Index;
using BadMishka.DocumentFormat.LuceneIndex.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BadMishka.DocumentFormat.LuceneIndex.Search
{
    public static class SimilarityUtil
    {

        private static readonly float[] s_normTable;

        static SimilarityUtil()
        {
            s_normTable = CreateNormalizedTable();
        }

        static float[] CreateNormalizedTable()
        {
            float[] result = new float[256];
            for (int i = 0; i < 256; i++)
                result[i] = i / 255.0F;
            return result;
        }

        /// <summary>
        /// Normalizes the value by un-scaling the byte value into a float
        /// e.g. approximately 1/sqrt(numTerms)
        /// </summary>
        /// <param name="value">The value to normalize.</param>
        /// <returns>The normalized value.</returns>
        internal static float Normalize(byte value)
        {
            return s_normTable[value & 0xFF];
        }

        /// <summary>
        /// Calculates the coordination factor, a value that rewards documents with a higher
        /// score when matching more terms of a query.
        /// </summary>
        /// <param name="overlap">The number of overlaps found in a document.</param>
        /// <param name="maxOverlap">The max number of overlaps allowed per document.</param>
        /// <returns>The coordination factor.</returns>
        internal static float CalculateCoordinationFactor(int overlap, int maxOverlap)
        {
            return overlap / (float)maxOverlap;
        }

        /// <summary>
        /// Returns the calculated term frequency for a document. e.g. tf(terms in document) = sqrt(frequency)
        /// </summary>
        /// <param name="frequencyOfTerm">The number of times a term appears in a document.</param>
        /// <returns>The term frequency.</returns>
        public static float CalculateTermFrequency(int frequencyOfTerm)
        {
            return (float)Math.Sqrt(frequencyOfTerm);
        }

        /// <summary>
        /// Returns the calculated term frequency for a document. e.g. tf(terms in document) = sqrt(frequency)
        /// </summary>
        /// <param name="frequencyOfTerm">The number of times a term appears in a document.</param>
        /// <returns>The term frequency.</returns>
        public static float CalculateTermFrequency(float frequencyOfTerm)
        {
            return (float)Math.Sqrt(frequencyOfTerm);
        }

        public static float CalculateInverseDocumentFrequency(Term term, ISearcher searcher)
        {
            // Use TotalDcoumentCount instead of numDocs() because its proportional to GetDocumentFrequencyForTerm,
            // i.e., when one is inaccurate, so is the other, and in the same way.
            return CalculateInverseDocumentFrequency(searcher.GetDocumentFrequencyForTerm(term), searcher.TotalDocumentCount);
        }

        public static float CalculateInverseDocumentFrequency(int documentFrequncy, int totalDocumentCount)
        {
            return (float)(Math.Log(totalDocumentCount / (double)(documentFrequncy + 1)) + 1.0);
        }

        /// <summary>
        /// Encodes a normalization factor for storage in an index.
        /// </summary>
        /// <remarks>
        ///     <para>
        ///         The encoding uses a five-bit exponent and three-bit mantissa, thus
        ///         representing values from around 7x10^9 to 2x10^-9 with about one
        ///         significant decimal digit of accuracy.  Zero is also represented.
        ///         Negative numbers are rounded up to zero.
        ///     </para>
        ///     <para>
        ///         Values too large to represent
        ///         are rounded down to the largest representable value.  Positive values too
        ///         small to represent are rounded up to the smallest positive representable
        ///         value.
        ///     </para>
        /// </remarks>
        /// <param name="value">The value to be encoded.</param>
        /// <returns>The encoded <see cref="byte"/> value of the float.</returns>
        /// <see cref="Document.Field.Boost"/>
        public static byte EncodeNormalization(float value)
        {
            return value.ToByte();
        }
    }
}


text:
var path = require('canonical-path');

var mockPackage = require('../mocks/mockPackage');
var Dgeni = require('dgeni');

describe("checkAnchorLinks", function() {
  var processor, mockLog;

  function checkWarning(link, doc) {
    expect(mockLog.warn).toHaveBeenCalled();
    expect(mockLog.warn.calls.first().args[0]).toContain(doc);
    expect(mockLog.warn.calls.first().args[0]).toContain(link);
  }

  beforeEach(function() {
    var testPackage = mockPackage();
    var dgeni = new Dgeni([testPackage]);
    var injector = dgeni.configureInjector();

    processor = injector.get('checkAnchorLinksProcessor');
    mockLog = injector.get('log');
  });

  it("should warn when there is a dangling link", function() {
    processor.$process([{ renderedContent: '', outputPath: 'doc/path.html', path: 'doc/path' }]);
    checkWarning('foo', 'doc/path.html');
  });

  it("should not warn when there is a page for a link", function() {
    processor.$process([
      { renderedContent: '', outputPath: 'doc/path.html', path: 'doc/path' },
      { renderedContent: 'CONTENT OF FOO', outputPath: 'foo.html', path: 'foo' }
    ]);
    expect(mockLog.warn).not.toHaveBeenCalled();
  });

  it('should match links who are prone to uri encoding', function() {
    processor.$process([
      { renderedContent: '', outputPath: 'doc/path.html', path: 'doc/path' },
      { renderedContent: 'CONTENT OF FOO', outputPath: 'doc/Foo extends Bar.html', path: 'doc/Foo extends Bar' }
    ])
    expect(mockLog.warn).not.toHaveBeenCalled();
  });

  it("should not warn if the link matches a path after it has been modified with a path variant", function() {
    processor.$process([
      { renderedContent: '', outputPath: 'doc/path.html', path: 'doc/path' },
      { renderedContent: 'CONTENT OF FOO', outputPath: 'foo.html', path: 'foo/' }
    ]);
    expect(mockLog.warn).not.toHaveBeenCalled();
  });

  it("should skip files that do not pass the `checkDoc` method", function() {
    processor.$process([
      { renderedContent: '', outputPath: 'x.js', path: 'x' },
      { renderedContent: '', outputPath: 'x.html' }
    ]);
    expect(mockLog.warn).not.toHaveBeenCalled();
  });

  it("should skip links that match the `ignoredLinks` property", function() {
    processor.$process([
      { renderedContent: 'foo', outputPath: 'x.html', path: 'x' },
      { renderedContent: 'foo', outputPath: 'a.html', path: 'a' },
      { renderedContent: 'foo', outputPath: 'c.html', path: 'c' },
      { renderedContent: 'Accessibility', outputPath: 'c.html', path: 'c' }
    ]);
    expect(mockLog.warn).not.toHaveBeenCalled();
  });

  it("should not warn for links to named anchors", function() {
    processor.$process([
      { renderedContent: 'footo foo', outputPath: 'x.html', path: 'x' },
      { renderedContent: 'foo', outputPath: 'a.html', path: 'a'},
      { renderedContent: 'foo', outputPath: 'b.html', path: 'b'},
      { renderedContent: 'foo', outputPath: 'c.html', path: 'c'},
      { renderedContent: 'foo', outputPath: 'd.html', path: 'd'}
    ]);
    expect(mockLog.warn).not.toHaveBeenCalled();
  });

  it("should not warn for links to elements defined by id", function() {
    processor.$process([
      { renderedContent: '
foo
to foo', outputPath: 'x.html', path: 'x' },
      { renderedContent: 'foo', outputPath: 'a.html', path: 'a'},
      { renderedContent: 'foo', outputPath: 'b.html', path: 'b'},
      { renderedContent: 'foo', outputPath: 'c.html', path: 'c'},
      { renderedContent: 'foo', outputPath: 'd.html', path: 'd'}
    ]);
    expect(mockLog.warn).not.toHaveBeenCalled();
  });

  it("should warn for internal, same page, dangling links", function() {
    processor.$process([
      { renderedContent: 'to foo', outputPath: 'x.html', path: 'x' }
    ]);
    checkWarning('#foo', 'x.html');
  });

  it("should warn for internal, cross page, dangling links", function() {
    processor.$process([
      { renderedContent: 'foo', outputPath: 'x.html', path: 'x' },
      { renderedContent: 'to bar', outputPath: 'y.html', path: 'y' }
    ]);
    checkWarning('x#bar', 'y.html');
  });

  it("should skip non-anchor elements", function() {
    processor.$process([
      { renderedContent: '

', outputPath: 'c.html', path: 'c' }
    ]);
    expect(mockLog.warn).not.toHaveBeenCalled();
  });
});