text:
.. _dojo/contentHandlers:

====================
dojo.contentHandlers
====================

:Project owner: Peter Higgins
:since: V1.4

.. contents ::
   :depth: 2

dojo.contentHandlers is an object containing several pre-defined "handlers" for Ajax traffic, exposed as a public API to allow your own custom handlers to be mixed in.

Usage
=====

The most common usage of contentHandlers is indirect. When making an Ajax call, the "handleAs" attribute is used to lookup in the dojo.contentHandlers dictionary. The function defined in the dictionary with a matching key is called, passing the XHR object used for the Ajax call. The **return** value from a contentHandler function is then passed to any "load", "handle" or callback functions.

Default contentHandler
----------------------

The default contentHandler is text, and requires no action:

.. js ::

     require(["dojo/_base/xhr"], function(xhr){
        xhr.get({
           url:"foo.txt",
           load: function(data){
              // this uses the default dojo.contentHandlers.text. It simply returns plaintext.
           }
        });
     });

Available Handlers
------------------

There are several pre-defined contentHandlers available to use. The value represents the key in the handlers map.

* **text** (default) - Simply returns the response text
* **json** - Converts response text into a JSON object
* **xml** - Returns a XML document
* **javascript** - Evaluates the response text
* **json-comment-filtered** - A (arguably unsafe) handler to preventing JavaScript hijacking
* **json-comment-optional** - A handler which detects the presence of a filtered response and toggles between json or json-comment-filtered appropriately.

Examples
========

Using a pre-defined handler
---------------------------

This example shows, how to use the pre-defined json contentHandler:

.. js ::

  require(["dojo/_base/xhr"], function(xhr){
     xhr.get({
        url:"foo.json",
        // here comes the contentHandler:
        handleAs: "json",
        load: function(data){
           if(data && !data.error){
              // see if our response contains an `error` member. { error:"Something is wrong" } for example
           }else{
              // something went wrong :)
           }
        }
     });
  });

Creating a custom handler
-------------------------

To create a custom contentHandler, simply mix a new key into the dojo.contentHandlers object defining the 'handleAs' value. The XHR object is passed to this function. For example:

.. js ::

  require(["dojo/_base/lang", "dojo/_base/xhr"], function(lang, xhr){
     lang.mixin(xhr.contentHandlers, {
        "makeUpper": function(req){
           return req.responseText.toUpperCase();
        }
     });

     // then later:
     xhr.post({
        url:"foo.php",
        handleAs:"makeUpper",
        load: function(data){
           // data is a CAPS version of the original responseText
        }
     });
  });

One can create any number of content handlers, and can do about anything they choose within the provided API. For instance, the original args used to create the XHR object are stored on the object itself as `ioArgs` (eg: xhr.ioArgs) and can be used to mix custom attributes and instructions to the handler.

For instance, we can create a handler that will populate a node with the response text automatically:

.. js ::

  require(["dojo/_base/xhr", "dojo/dom"], function(xhr, dom){
      var ioArgs = {
          url:"foo.html",
          handleAs:"loadNode",
          node: "someId"
      };

      // you don't need to mix(), you can just set the object directly if you prefer:
      xhr.contentHandlers.loadNode = function(req){
          var n = dom.byId(ioArgs.node);
          n && (n.innerHTML = req.responseText);
      };

      xhr.get(ioArgs);
  });

This will inject foo.html content into a node with id="someId". A side effect of the above example would be any callbacks passed to something handled by the "loadNode" contentHandler would not also get a copy of the content. You should return a value from a contentHandler.

Using dual handlers
-------------------

The other contentHandlers are all functions. If you like, you can define a new handler that acts as if it were another handler and doing something else. Simply call the other contentHandler passing the xhr reference you were passed in your custom handler:

.. js ::

    require(["dojo/_base/xhr", "dojo/_base/lang"], function(xhr, lang){
        xhr.contentHandlers.wrappedJSON = function(req){
            // like handleAs:"json", but mixes an additional bit into the response always.
            var json = xhr.contentHandles.json(req);
            return lang.mixin(json, { _wrapped_by_app:true });
        };

        xhr.get({
            url:"users.json",
            handleAs:"wrappedJSON",
            load: function(data){
                if(data._wrapped_by_app){
                    console.log("neat!");
                }
            }
        });
    });

Overwriting a handler
---------------------

Standard AOP techniques apply. If you find yourself needing to *replace* a contentHandler but preserve the original behavior, simply duck-punch around it:

.. js ::

    require(["dojo/_base/xhr"], function(xhr){
        // a handler that always escapes html fragments. not exceptionally useful though:
        var oldtext = xhr.contentHandlers.text;
        xhr.contentHandles.text = function(req){
            return oldtext.apply(this, arguments).replace("<", "<");
        };
    });

Notes
=====

This functionality is "new" in Dojo 1.4. An alias to the "private" dojo._contentHandlers will remain in place until 2.0. Version prior to 1.4 can use the "private" alias the same way as outlined in this document.


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		<title>Usambara akalat factsheet on ARKive - Sheppardia montana</title>
        <link rel="canonical" href="http://www.arkive.org/usambara-akalat/sheppardia-montana/" />
		<link rel="stylesheet" type="text/css" media="screen,print" href="/rcss/factsheet.css" />
		<link rel="icon" href="/favicon.ico" type="image/x-icon" />
		<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />

Usambara akalat (Sheppardia montana)

Also known as:
Usambara ground robin

Synonyms:
Dryocichloides montanus

French:
Cossyphe des Usambaras

Kingdom	Animalia

Phylum	Chordata

Class	Aves

Order	Passeriformes

Family	Muscicapidae

Genus	Sheppardia (1)

Classified as Endangered (EN) on the IUCN Red List (1).

Information on the Usambara akalat is currently being researched and written and will appear here shortly.

This information is awaiting authentication by a species expert, and will be updated as soon as possible. If you are able to help please contact: arkive@wildscreen.org.uk

IUCN Red List  (January, 2009)
http://www.iucnredlist.org

redpajama_set_name: RedPajamaGithub


text:
package com.azure.resourcemanager.attestation.implementation;

import com.azure.core.management.Region;
import com.azure.core.management.SystemData;
import com.azure.core.util.Context;
import com.azure.resourcemanager.attestation.fluent.models.AttestationProviderInner;
import com.azure.resourcemanager.attestation.fluent.models.PrivateEndpointConnectionInner;
import com.azure.resourcemanager.attestation.models.AttestationProvider;
import com.azure.resourcemanager.attestation.models.AttestationServiceCreationParams;
import com.azure.resourcemanager.attestation.models.AttestationServiceCreationSpecificParams;
import com.azure.resourcemanager.attestation.models.AttestationServicePatchParams;
import com.azure.resourcemanager.attestation.models.AttestationServiceStatus;
import com.azure.resourcemanager.attestation.models.PrivateEndpointConnection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public final class AttestationProviderImpl
    implements AttestationProvider, AttestationProvider.Definition, AttestationProvider.Update {
    private AttestationProviderInner innerObject;

    private final com.azure.resourcemanager.attestation.AttestationManager serviceManager;

    public String id() {
        return this.innerModel().id();
    }

    public String name() {
        return this.innerModel().name();
    }

    public String type() {
        return this.innerModel().type();
    }

    public String location() {
        return this.innerModel().location();
    }

    public Map<String, String> tags() {
        Map<String, String> inner = this.innerModel().tags();
        if (inner != null) {
            return Collections.unmodifiableMap(inner);
        } else {
            return Collections.emptyMap();
        }
    }

    public SystemData systemData() {
        return this.innerModel().systemData();
    }

    public String trustModel() {
        return this.innerModel().trustModel();
    }

    public AttestationServiceStatus status() {
        return this.innerModel().status();
    }

    public String attestUri() {
        return this.innerModel().attestUri();
    }

    public List<PrivateEndpointConnection> privateEndpointConnections() {
        List<PrivateEndpointConnectionInner> inner = this.innerModel().privateEndpointConnections();
        if (inner != null) {
            return Collections
                .unmodifiableList(
                    inner
                        .stream()
                        .map(inner1 -> new PrivateEndpointConnectionImpl(inner1, this.manager()))
                        .collect(Collectors.toList()));
        } else {
            return Collections.emptyList();
        }
    }

    public Region region() {
        return Region.fromName(this.regionName());
    }

    public String regionName() {
        return this.location();
    }

    public AttestationProviderInner innerModel() {
        return this.innerObject;
    }

    private com.azure.resourcemanager.attestation.AttestationManager manager() {
        return this.serviceManager;
    }

    private String resourceGroupName;

    private String providerName;

    private AttestationServiceCreationParams createCreationParams;

    private AttestationServicePatchParams updateUpdateParams;

    public AttestationProviderImpl withExistingResourceGroup(String resourceGroupName) {
        this.resourceGroupName = resourceGroupName;
        return this;
    }

    public AttestationProvider create() {
        this.innerObject =
            serviceManager
                .serviceClient()
                .getAttestationProviders()
                .createWithResponse(resourceGroupName, providerName, createCreationParams, Context.NONE)
                .getValue();
        return this;
    }

    public AttestationProvider create(Context context) {
        this.innerObject =
            serviceManager
                .serviceClient()
                .getAttestationProviders()
                .createWithResponse(resourceGroupName, providerName, createCreationParams, context)
                .getValue();
        return this;
    }

    AttestationProviderImpl(String name, com.azure.resourcemanager.attestation.AttestationManager serviceManager) {
        this.innerObject = new AttestationProviderInner();
        this.serviceManager = serviceManager;
        this.providerName = name;
        this.createCreationParams = new AttestationServiceCreationParams();
    }

    public AttestationProviderImpl update() {
        this.updateUpdateParams = new AttestationServicePatchParams();
        return this;
    }

    public AttestationProvider apply() {
        this.innerObject =
            serviceManager
                .serviceClient()
                .getAttestationProviders()
                .updateWithResponse(resourceGroupName, providerName, updateUpdateParams, Context.NONE)
                .getValue();
        return this;
    }

    public AttestationProvider apply(Context context) {
        this.innerObject =
            serviceManager
                .serviceClient()
                .getAttestationProviders()
                .updateWithResponse(resourceGroupName, providerName, updateUpdateParams, context)
                .getValue();
        return this;
    }

    AttestationProviderImpl(
        AttestationProviderInner innerObject, com.azure.resourcemanager.attestation.AttestationManager serviceManager) {
        this.innerObject = innerObject;
        this.serviceManager = serviceManager;
        this.resourceGroupName = Utils.getValueFromIdByName(innerObject.id(), "resourceGroups");
        this.providerName = Utils.getValueFromIdByName(innerObject.id(), "attestationProviders");
    }

    public AttestationProvider refresh() {
        this.innerObject =
            serviceManager
                .serviceClient()
                .getAttestationProviders()
                .getByResourceGroupWithResponse(resourceGroupName, providerName, Context.NONE)
                .getValue();
        return this;
    }

    public AttestationProvider refresh(Context context) {
        this.innerObject =
            serviceManager
                .serviceClient()
                .getAttestationProviders()
                .getByResourceGroupWithResponse(resourceGroupName, providerName, context)
                .getValue();
        return this;
    }

    public AttestationProviderImpl withRegion(Region location) {
        this.createCreationParams.withLocation(location.toString());
        return this;
    }

    public AttestationProviderImpl withRegion(String location) {
        this.createCreationParams.withLocation(location);
        return this;
    }

    public AttestationProviderImpl withProperties(AttestationServiceCreationSpecificParams properties) {
        this.createCreationParams.withProperties(properties);
        return this;
    }

    public AttestationProviderImpl withTags(Map<String, String> tags) {
        if (isInCreateMode()) {
            this.createCreationParams.withTags(tags);
            return this;
        } else {
            this.updateUpdateParams.withTags(tags);
            return this;
        }
    }

    private boolean isInCreateMode() {
        return this.innerModel().id() == null;
    }
}


text:
package stocks;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import outgoing_data_sources.DummyService;
import trade_types.MarketTrade;
import trade_types.Trade;
import utilities.GeneralToolKit;

/**
 * Represents a Trader's Portfolio
 *
 * @author Steven Shaw
 * @email  sps5688@rit.edu
 *
 */
@SuppressWarnings("serial")
public class Portfolio implements Serializable {

	private List<Trade> positions = new ArrayList<Trade>();
	private List<Trade> tradeHistory = new ArrayList<Trade>();
	private ArrayList<String> watchList = new ArrayList<String>();
	private double moneyAmount;
	private double availableFunds;
	private double netWorth;
	private String accountName;

	public Portfolio(String accountName, double funds) {
		moneyAmount = funds;
		availableFunds = funds;
		netWorth = funds;
		this.accountName = accountName;
	}

	/**
	 * Retrieves the trader's currently owned stocks
	 *
	 * @return List of Trades
	 */
	public List<Trade> getStocks() {
		return positions;
	}

	/**
	 * Processes the new Trade
	 *
	 * @param newTrade the trade to be processed
	 */
	public void addStockTransaction(Trade newTrade) {
		// Sends trade through outgoing service and updates stock price
		DummyService service = new DummyService();
		newTrade = service.executeOrder(newTrade);

		// Searches positions list
		boolean found = false;
		for (int i = 0; i < positions.size(); i++) {
			// If stock is already owned
			if (positions.get(i).getSymbol().symbol.equals(newTrade.getSymbol().symbol)) {

				// Creates a new object so trade history does not have the same object address
				// Currently only Market Trades are implemented
				Trade existingTrade = null;
				if(newTrade.getTradeType().equals("market")){
					existingTrade = new MarketTrade(newTrade.getOrderType(), newTrade.getSymbol(), newTrade.getShares());
				}else if(newTrade.getTradeType().equals("market on close")){
					existingTrade = new MarketTrade(newTrade.getOrderType(), newTrade.getSymbol(), newTrade.getShares());
				}else if(newTrade.getTradeType().equals("limit")){
					existingTrade = new MarketTrade(newTrade.getOrderType(), newTrade.getSymbol(), newTrade.getShares());
				}else if(newTrade.getTradeType().equals("stop limit")){
					existingTrade = new MarketTrade(newTrade.getOrderType(), newTrade.getSymbol(), newTrade.getShares());
				}else if(newTrade.getTradeType().equals("stop")){
					existingTrade = new MarketTrade(newTrade.getOrderType(), newTrade.getSymbol(), newTrade.getShares());
				}else if(newTrade.getTradeType().equals("trailing stop dolar")){
					existingTrade = new MarketTrade(newTrade.getOrderType(), newTrade.getSymbol(), newTrade.getShares());
				}else if(newTrade.getTradeType().equals("trailing stop percent")){
					existingTrade = new MarketTrade(newTrade.getOrderType(), newTrade.getSymbol(), newTrade.getShares());
				}

				existingTrade.setPrice(newTrade.getPrice());
				tradeHistory.add(existingTrade);

				// Updates share amount if already owned
				updateShareAmount(existingTrade.getSymbol(), existingTrade.getShares(), existingTrade.getOrderType());

				found = true;
				break;
			}
		}

		// If not owned, add to positions list
		if (found == false) {
			tradeHistory.add(newTrade);
			positions.add(newTrade);
		}
	}

	/**
	 * Removes a stock from a Trader's position list
	 *
	 * @param toRemove Stock that will be removed
	 */
	public void removeStock(Stock toRemove) {
		for (int i = 0; i < positions.size(); i++) {
			if (positions.get(i).getSymbol() == toRemove) {
				positions.remove(positions.get(i));
			}
		}
	}

	/**
	 * Returns how many stocks the Trader owns
	 *
	 * @return
	 */
	public int getPositionsSize() {
		return positions.size();
	}

	/**
	 * Sets the money amount for the Trader
	 *
	 * @param amount
	 */
	public void setMoneyAmount(double amount) {
		moneyAmount = amount;
	}

	/**
	 * Gets the money amount for the Trader
	 *
	 * @return
	 */
	public double getMoneyAmount() {
		return moneyAmount;
	}

	/**
	 * Sets the Trader's account name
	 *
	 * @param name
	 */
	public void setAccountName(String name) {
		accountName = name;
	}

	/**
	 * Gets the Trader's account name
	 *
	 * @return
	 */
	public String getAccountName() {
		return accountName;
	}

	/**
	 * Sets the Trader's available funds
	 *
	 * @param amount
	 */
	public void setAvailableFunds(double amount) {
		availableFunds = amount;
	}

	/**
	 * Gets the Trader's available funds
	 *
	 * @return
	 */
	public double getAvailableFunds() {
		return availableFunds;
	}

	/**
	 * Updates how much money the Trader has left to spend
	 *
	 * @param amount
	 */
	public void updateAvailableFunds(double amount) {
		availableFunds += amount;
	}

	/**
	 * Prints out the Trader's currently owned stocks
	 *
	 */
	public void printPortfolio() {
		Stock curStock;
		int curShares;
		double curPrice;
		Trade curTrade;

		for (int i = 0; i < positions.size(); i++) {
			curTrade = positions.get(i);
			curShares = curTrade.getShares();
			curStock = curTrade.getSymbol();
			curPrice = curTrade.getPrice();

			System.out.println(curStock.symbol + " " + curShares + " "
					+ curPrice);
		}
	}

	/**
	 * Prints out the Trader's watch list
	 *
	 */
	public void printWatchList() {
		for (String curStock : watchList) {
			System.out.print(curStock + " ");
		}
		System.out.println();
	}

	/**
	 * Adds a symbol to the Trader's watch list
	 *
	 * @param symbol
	 */
	public void addToWatchList(String symbol) {
		if(GeneralToolKit.verifySymbol(symbol)){
			watchList.add(symbol);
		}
	}

	/**
	 * Gets the number of shares that the Trader owns of a stock
	 *
	 * @param symbol the stock for lookup
	 * @return number of shares
	 */
	public int getShareAmount(Stock symbol) {
		Trade curTrade;
		int shareTotal = 0;

		for (int i = 0; i < positions.size(); i++) {
			curTrade = positions.get(i);

			if (curTrade.getSymbol() == symbol) {
				shareTotal += curTrade.getShares();
			}
		}
		return shareTotal;
	}

	/**
	 * Returns the average priced paid for a stock
	 *
	 * @param symbol the stock for lookup
	 * @return average priced paid
	 */
	public double getPriceAmount(Stock symbol) {
		Trade curTrade;
		double prices = 0.0;
		int count = 0;

		// Adds up all the prices and counts how many times it was bought
		for (int i = 0; i < positions.size(); i++) {
			curTrade = positions.get(i);

			if (curTrade.getSymbol().symbol.equals(symbol.symbol)) {
				prices += curTrade.getPrice();
				count++;
			}
		}

		// Computes average price
		if (count != 0) {
			return (prices / count);
		} else {
			return 0;
		}
	}

	/**
	 * Prints the Trader's transactions
	 */
	public void printTradeHistory() {
		Trade curTrade;
		int curShares;
		Stock curStock;
		double curPrice;
		String curOrderType;

		// Iterates through tradeHistory list and prints out information
		for (int i = 0; i < tradeHistory.size(); i++) {
			curTrade = tradeHistory.get(i);
			curOrderType = curTrade.getOrderType();
			curShares = curTrade.getShares();
			curStock = curTrade.getSymbol();
			curPrice = curTrade.getPrice();

			System.out.println(curOrderType + " " + curStock.symbol + " " + curShares + " " + curPrice);
		}
	}

	/**
	 * Updates share amount for an already owned stock
	 *
	 * @param toUpdate
	 * @param shareAmount
	 * @param orderType
	 */
	public void updateShareAmount(Stock toUpdate, int shareAmount, String orderType) {
		int shares = 0;
		int newShares = 0;

		// Searches for stock to update
		for (int i = 0; i < positions.size(); i++) {
			if (positions.get(i).getSymbol() == toUpdate) {
				shares = positions.get(i).getShares();

				if (orderType.equals("Buy")) {
					newShares = shares + shareAmount;

					// Updates share amount
					positions.get(i).setShares(newShares);
				} else {
					newShares = shares - shareAmount;

					// If no shares are left, remove from positions list
					// Otherwise, update share amount
					if (newShares == 0) {
						removeStock(toUpdate);
					} else {
						positions.get(i).setShares(newShares);
					}
				}
			}
		}
	}

	/**
	 * Returns the Trader's watch list
	 *
	 * @return
	 */
	public ArrayList<String> getWatchList() {
		return watchList;
	}

	/**
	 * Removes a stock from the Trader's watch list
	 *
	 * @param symbol
	 */
	public void removeFromWatchList(String symbol) {
		if(GeneralToolKit.verifySymbol(symbol)){
			for (int i = 0; i < watchList.size(); i++) {
				if (watchList.get(i).equals(symbol)) {
					watchList.remove(watchList.get(i));
				}
			}
		}
	}

	/**
	 * Updates the Trader's net worth
	 *
	 * @param amount
	 */
	public void updateNetWorth(double amount) {
		netWorth += amount;
	}

	/**
	 * Returns the trader's net worth
	 *
	 * @return
	 */
	public double getNetWorth() {
		return netWorth;
	}

	/**
	 * Returns the percent change from when the Trader started
	 *
	 * @return
	 */
	public String getPercentChange() {
		StringBuilder result = new StringBuilder();
		double difference = netWorth - moneyAmount;

		if (difference < 0) {
			result.append("-");
		} else if (difference > 0) {
			result.append("+");
		} else {
			result.append("");
		}

		double percentChange = ((moneyAmount - netWorth) / netWorth) * 100;
		result.append(Double.toString(percentChange) + "%");

		return result.toString();
	}
}


text:
"use strict";

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var repl = require('repl');
var net = require('net');
var Promise = require('bluebird');
var async = require('async');
var fs = require('fs');
var util = require('util');
var chalk = require('chalk');
var extend = require('extend');
var ModuleBase = require('../Base');

/// Raw string

var RawString = function RawString(text) {
	_classCallCheck(this, RawString);

	this.text = text;
};
// Error

var HelpStringError = function (_Error) {
	_inherits(HelpStringError, _Error);

	function HelpStringError() {
		_classCallCheck(this, HelpStringError);

		return _possibleConstructorReturn(this, Object.getPrototypeOf(HelpStringError).apply(this, arguments));
	}

	return HelpStringError;
}(Error);

/// Parse cmd

function cmdParse(cmd) {
	var output = [];
	var matchRegex = /[^\s"']+|"((?:\\"|[^"])*?)"|'((?:\\'|[^'])*?)'/g;
	var match;
	while (match = matchRegex.exec(cmd)) {
		if (match[1]) output.push(match[1]);else if (match[2]) output.push(match[2]);else output.push(match[0]);
	}
	return output;
}

/**
 * Convert the object to an error to append to the
 * logger
 */
function asError(error) {
	if (!(error instanceof Error)) return error;
	return {
		message: error.message,
		name: error.name,
		code: error.code,
		signal: error.signal,
		stack: error.stack || error.toString()
	};
}

/**
 * REPL module
 */

var REPL = function (_ModuleBase) {
	_inherits(REPL, _ModuleBase);

	function REPL() {
		_classCallCheck(this, REPL);

		return _possibleConstructorReturn(this, Object.getPrototypeOf(REPL).apply(this, arguments));
	}

	_createClass(REPL, [{
		key: 'moduleSetup',

		/**
   * REPL mode
   */
		value: function moduleSetup() {
			this._servers = [];
			this._unixSockets = [];
			this._interfaces = [];
			this._commands = {};
			this._id = 0;
			this._chalk = new chalk.constructor({ enabled: true });

			// Get the options
			var serverOptions = this.options.server;
			if (serverOptions === false) return;

			// Invalid configuration
			if (!serverOptions) throw new Error("Invalid configuration");
			// Array configuration
			if (!Array.isArray(serverOptions)) serverOptions = [serverOptions];

			var promises = [];
			var self = this;
			serverOptions.forEach(function (options) {
				// Options
				if (!options) throw new Error("Invalid configuration");

				// Create the server
				var server = net.createServer(self._onConnection.bind(self));
				self._servers.push(server);

				var promise = Promise.resolve(true);

				var isUDS = options.path || typeof options === 'string';
				var pathUDS = options.path || options;

				self.logger.info({}, "Creating server using: " + JSON.stringify(options));

				if (isUDS) {
					promise = promise.then(function () {
						return self.removeUnixDomainSocket(pathUDS);
					});
				}

				// Start listening
				promise = promise.then(function () {
					return Promise.fromCallback(function (callback) {
						server.listen(options, callback);
					});
				});

				// When Unix domain socket, save it so we can cleanup
				if (isUDS) {
					promise = promise.then(function () {
						self._unixSockets.push(pathUDS);
					});
				}
				promises.push(promise);
			});

			// Help
			this.register('help', this.CMD_help.bind(this), 'Prints help for command');

			//
			return Promise.all(promises);
		}
		/**
   *
   */

	}, {
		key: 'removeUnixDomainSocket',
		value: function removeUnixDomainSocket(path) {
			return new Promise(function (resolve, reject) {
				var socket = net.connect({ path: path });
				socket.on('connect', function () {
					reject();
					socket.end();
				});
				socket.on('error', function () {
					fs.unlink(path, function (err) {
						resolve();
					});
				});
			});
		}
		/**
   * Close every server for this object
   */

	}, {
		key: 'moduleClose',
		value: function moduleClose() {
			var self = this;

			var unixSockets = this._unixSockets;
			this._unixSockets = [];

			var servers = this._servers;
			this._servers = [];

			var interfaces = this._interfaces;
			this._interfaces = [];

			var asyncEach = Promise.promisify(async.each);

			function unlinkUnixSocketsIterator(unixSocket, next) {
				fs.unlink(unixSocket, function () {
					next();
				});
			};
			function closeIterator(obj, next) {
				try {
					obj.close();
				} catch (err) {
					self.logger.error(err);
				}
				next();
			};

			// Close all sockets
			return asyncEach(servers, closeIterator).then(function () {
				return asyncEach(unixSockets, unlinkUnixSocketsIterator);
			}).then(function () {
				return asyncEach(interfaces, closeIterator);
			});
		}
		/**
   * On connection
   */

	}, {
		key: '_onConnection',
		value: function _onConnection(socket) {
			var self = this;

			var interfaceID = this._id++;

			var replInterface = repl.start({
				input: socket,
				output: socket,
				ignoreUndefined: true,
				useColors: true,
				writer: function writer(arg) {
					if (typeof arg === 'undefined') return;
					if (arg instanceof RawString) {
						return arg.text;
					} else {
						return util.inspect(arg);
					}
				},
				eval: function _eval(cmd, context, filename, callback) {
					Promise.try(function () {
						return self._evalCommand(cmd, context, filename, replInterface, interfaceID);
					}).catch(function (err) {
						self.logger.error(extend(asError(err), { cmd: cmd, interfaceID: interfaceID }), "Error running command");
						return new RawString(self._chalk.red('Error: ') + (err.message || err));
					}).asCallback(callback);
				}
			}).on('close', function () {
				var index = self._interfaces.indexOf(replInterface);
				if (index >= 0) self._interfaces.splice(index, 1);
				socket.end();
			});
			this._interfaces.push(replInterface);
			this.logger.info({ interfaceID: interfaceID, socket: socket }, "Registering interface");
		}
		/**
   * Eval the command
   */

	}, {
		key: '_evalCommand',
		value: function _evalCommand(cmd, context, filename, replInterface, interfaceID) {
			this.logger.info({ cmd: cmd, interfaceID: interfaceID }, "Evaluating command");

			cmd = cmd.trim();
			var cmdSplit = cmdParse(cmd);

			// Empty command
			if (!cmdSplit || cmdSplit.length <= 0) return;

			// Try to get the command
			var current = this._commands[cmdSplit[0]];
			if (!current) throw new Error("Invalid command");

			var validCommand;
			if (current.$cmd) validCommand = current;

			for (var i = 1, len = cmdSplit.length; i < len; ++i) {
				var item = cmdSplit[i];
				if (!current[item]) break;
				current = current[item];
				if (current.$cmd) validCommand = current;
			}
			var cmdData = {
				cmd: cmd,
				args: cmdSplit.slice(i)
			};
			if (!validCommand) throw new Error("Invalid command");
			return validCommand.$cmd.fn.apply(this, [cmdData].concat(cmdData.args));
		}
		/**
   * Auto register an object
   */

	}, {
		key: 'autoRegister',
		value: function autoRegister(obj, thisObj, filename) {
			var self = this;
			Object.getOwnPropertyNames(obj).forEach(function (name) {
				if (name.substr(0, 4) !== 'CMD_') return;
				var cmdName = name.substr(4);
				var cmd = cmdName.split(/(?=[A-Z])/).map(function (s) {
					return s.toLowerCase();
				});
				var fn = obj[name];
				self.register(cmd, fn.bind(thisObj), fn.help);
			});
		}
		/**
   * Register a command
   */

	}, {
		key: 'register',
		value: function register(cmd, fn, help) {
			if (typeof cmd === 'string') cmd = cmd.split(/\s+/);
			var current = this._commands;
			cmd.forEach(function (s) {
				current[s] = current[s] || {};
				current = current[s];
			});
			current.$cmd = {
				cmd: cmd,
				cmdStr: cmd.join(" "),
				fn: fn,
				help: help
			};
		}
		/**
   * Help command
   */

	}, {
		key: 'CMD_help',
		value: function CMD_help(cmd) {
			var self = this;

			var current = this._commands;
			for (var i = 0, len = cmd.args.length; i < len; ++i) {
				if (!current[cmd.args[i]]) return;
				current = current[cmd.args[i]];
			}

			var output = [];
			function buildOutput(cmd) {
				if (!cmd) return;

				if (cmd.$cmd) output.push(cmd.$cmd);

				for (var key in cmd) {
					if (key !== '$cmd') buildOutput(cmd[key]);
				}
			}
			buildOutput(current);

			var outputStr = output.map(function (cmd) {
				return '' + self._chalk.yellow(cmd.cmdStr) + ' ' + (cmd.help || '');
			});
			return new RawString(outputStr.join("\n"));
		}
	}]);

	return REPL;
}(ModuleBase);

module.exports = REPL;


text:
/**
 * this is a small sample script to use libmbfl.
 * Rui Hirokawa <hirokawa@php.net>
 *
 * this file is encoded in EUC-JP.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "mbfl/mbfilter.h"

int main(int argc, char **argv)
{
	enum mbfl_no_encoding no_encoding;
	enum mbfl_no_language no_language;
	mbfl_memory_device dev;
	mbfl_string string;
	int final = 0;
	int state = 0;

	if (argc < 3) {
		fprintf(stderr, "Usage: %s lang encoding\n", argv[0]);
		return EXIT_FAILURE;
	}

	if ((no_language = mbfl_name2no_language(argv[1])) ==
			mbfl_no_language_invalid) {
		printf("Unsupported NLS: %s\n", argv[1]);
		return EXIT_FAILURE;
	}

	if ((no_encoding = mbfl_name2no_encoding(argv[2])) ==
			mbfl_no_encoding_invalid) {
		printf("Unsupported encoding: %s\n", argv[2]);
		return EXIT_FAILURE;
	}

	do {
		mbfl_memory_device_init(&dev, 0, 4096);
		mbfl_string_init_set(&string, no_language, no_encoding);

		for (;;) {
			const int c = fgetc(stdin);

			if (c == EOF) {
				final = 1;
				break;
			} else if (c == 10) {
				if (state == 1) {
					state = 0;
					continue;
				}
				break;
			} else if (c == 13) {
				state = 1;
				break;
			}

			if (dev.pos >= dev.length) {
				if (dev.length + dev.allocsz < dev.length) {
					printf("Unable to allocate memory\n");
					return EXIT_FAILURE;
				}

				mbfl_memory_device_realloc(&dev, dev.length + dev.allocsz,
						dev.allocsz);
			}

			dev.buffer[dev.pos++] = (unsigned char)c;
		}

		mbfl_memory_device_result(&dev, &string);
		printf("%d\n", mbfl_strwidth(&string));
		mbfl_string_clear(&string);
	} while (!final);

	return EXIT_SUCCESS;
}


text:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/memory/shared_memory.h"
#include "content/common/content_export.h"
#include "content/common/media/video_capture.h"
#include "content/public/common/common_param_traits.h"
#include "gpu/command_buffer/common/mailbox_holder.h"
#include "ipc/ipc_message_macros.h"
#include "media/base/video_capture_types.h"
#include "media/base/video_frame.h"

#undef IPC_MESSAGE_EXPORT
#define IPC_MESSAGE_EXPORT CONTENT_EXPORT
#define IPC_MESSAGE_START VideoCaptureMsgStart

IPC_ENUM_TRAITS_MAX_VALUE(content::VideoCaptureState,
                          content::VIDEO_CAPTURE_STATE_LAST)
IPC_ENUM_TRAITS_MAX_VALUE(media::ResolutionChangePolicy,
                          media::RESOLUTION_POLICY_LAST)
IPC_ENUM_TRAITS_MAX_VALUE(media::VideoPixelFormat, media::PIXEL_FORMAT_MAX)
IPC_ENUM_TRAITS_MAX_VALUE(media::VideoFrame::StorageType,
                          media::VideoFrame::STORAGE_LAST)
IPC_ENUM_TRAITS_MAX_VALUE(media::VideoCapturePixelFormat,
                          media::VIDEO_CAPTURE_PIXEL_FORMAT_MAX)
IPC_ENUM_TRAITS_MAX_VALUE(media::VideoPixelStorage, media::PIXEL_STORAGE_MAX)

IPC_STRUCT_TRAITS_BEGIN(media::VideoCaptureParams)
  IPC_STRUCT_TRAITS_MEMBER(requested_format)
  IPC_STRUCT_TRAITS_MEMBER(resolution_change_policy)
IPC_STRUCT_TRAITS_END()

IPC_STRUCT_BEGIN(VideoCaptureMsg_BufferReady_Params)
  IPC_STRUCT_MEMBER(int, device_id)
  IPC_STRUCT_MEMBER(int, buffer_id)
  IPC_STRUCT_MEMBER(base::TimeTicks, timestamp)
  IPC_STRUCT_MEMBER(base::DictionaryValue, metadata)
  IPC_STRUCT_MEMBER(media::VideoPixelFormat, pixel_format)
  IPC_STRUCT_MEMBER(media::VideoFrame::StorageType, storage_type)
  IPC_STRUCT_MEMBER(gfx::Size, coded_size)
  IPC_STRUCT_MEMBER(gfx::Rect, visible_rect)
  IPC_STRUCT_MEMBER(gpu::MailboxHolder, mailbox_holder)
IPC_STRUCT_END()

// TODO(nick): device_id in these messages is basically just a route_id. We
// should shift to IPC_MESSAGE_ROUTED and use MessageRouter in the filter impls.

// Notify the renderer process about the state update such as
// Start/Pause/Stop.
IPC_MESSAGE_CONTROL2(VideoCaptureMsg_StateChanged,
                     int /* device id */,
                     content::VideoCaptureState /* new state */)

// Tell the renderer process that a new buffer is allocated for video capture.
IPC_MESSAGE_CONTROL4(VideoCaptureMsg_NewBuffer,
                     int /* device id */,
                     base::SharedMemoryHandle /* handle */,
                     int /* length */,
                     int /* buffer_id */)

// Tell the renderer process that it should release a buffer previously
// allocated by VideoCaptureMsg_NewBuffer.
IPC_MESSAGE_CONTROL2(VideoCaptureMsg_FreeBuffer,
                     int /* device id */,
                     int /* buffer_id */)

// Tell the renderer process that a Buffer is available from video capture, and
// send the associated VideoFrame constituient parts as IPC parameters.
IPC_MESSAGE_CONTROL1(VideoCaptureMsg_BufferReady,
                     VideoCaptureMsg_BufferReady_Params)

// Notify the renderer about a device's supported formats; this is a response
// to a VideoCaptureHostMsg_GetDeviceSupportedFormats request.
IPC_MESSAGE_CONTROL2(VideoCaptureMsg_DeviceSupportedFormatsEnumerated,
                     int /* device_id */,
                     media::VideoCaptureFormats /* supported_formats */)

// Notify the renderer about a device's format(s) in use; this is a response
// to a VideoCaptureHostMsg_GetDeviceFormatInUse request.
IPC_MESSAGE_CONTROL2(VideoCaptureMsg_DeviceFormatsInUseReceived,
                     int /* device_id */,
                     media::VideoCaptureFormats /* formats_in_use */)

// Start a video capture as |device_id|, a new id picked by the renderer
// process. The session to be started is determined by |params.session_id|.
IPC_MESSAGE_CONTROL3(VideoCaptureHostMsg_Start,
                     int /* device_id */,
                     media::VideoCaptureSessionId, /* session_id */
                     media::VideoCaptureParams /* params */)

// Pause the video capture specified by |device_id|.
IPC_MESSAGE_CONTROL1(VideoCaptureHostMsg_Pause,
                     int /* device_id */)

// Resume the video capture specified by |device_id|, |session_id| and
// |params|.
IPC_MESSAGE_CONTROL3(VideoCaptureHostMsg_Resume,
                     int, /* device_id */
                     media::VideoCaptureSessionId, /* session_id */
                     media::VideoCaptureParams /* params */)

// Close the video capture specified by |device_id|.
IPC_MESSAGE_CONTROL1(VideoCaptureHostMsg_Stop,
                     int /* device_id */)

// Tell the browser process that the renderer has finished reading from
// a buffer previously delivered by VideoCaptureMsg_BufferReady.
IPC_MESSAGE_CONTROL4(VideoCaptureHostMsg_BufferReady,
                     int /* device_id */,
                     int /* buffer_id */,
                     uint32 /* syncpoint */,
                     double /* consumer_resource_utilization */)

// Get the formats supported by a device referenced by |capture_session_id|.
IPC_MESSAGE_CONTROL2(VideoCaptureHostMsg_GetDeviceSupportedFormats,
                     int /* device_id */,
                     media::VideoCaptureSessionId /* session_id */)

// Get the format(s) in use by a device referenced by |capture_session_id|.
IPC_MESSAGE_CONTROL2(VideoCaptureHostMsg_GetDeviceFormatsInUse,
                     int /* device_id */,
                     media::VideoCaptureSessionId /* session_id */)


text:
import ezibpy
import time

# initialize ezIBpy
ibConn = ezibpy.ezIBpy()

# connect to IB (7496/7497 = TWS, 4001 = IBGateway)
ibConn.connect(clientId=100, host="localhost", port=4001)

# create some contracts using dedicated methods
put  = ibConn.createOptionContract("AAPL", expiry="20161021", strike=117.0, otype="PUT")
call = ibConn.createOptionContract("AAPL", expiry="20161021", strike=117.0, otype="CALL")

# request market data for all created contracts
ibConn.requestMarketData()

# wait 30 seconds
time.sleep(30)

# print market data
print("Options Data")
print(ibConn.optionsData)

# cancel market data request & disconnect
ibConn.cancelMarketData()
ibConn.disconnect()


text:
module.exports = {
  getProducts: async (req, res) => {
    const page = req.param('page')

    const amountOfProducts = await Product
      .count()
      .catch(error => res.serverError(error))

    const products = await Product
      .find()
      .populate('user', { select: ['name'] })
      .paginate({page, limit: 6})
      .catch(error => res.serverError(error))

    return res.json({
      products,
      amountOfProducts
    })
  }
}


text:
ModulePhysics::ModulePhysics(Application* app, bool start_enabled) : Module(app, start_enabled)
{
	world = NULL;
	mouse_joint = NULL;
	debug = false;
}

// Destructor
ModulePhysics::~ModulePhysics()
{
}

bool ModulePhysics::Start()
{
	LOG("Creating Physics 2D environment");

	world = new b2World(b2Vec2(GRAVITY_X, 20));
	world->SetContactListener(this);

	// needed to create joints like mouse joint
	b2BodyDef bd;
	ground = world->CreateBody(&bd);

	return true;
}

//
update_status ModulePhysics::PreUpdate()
{
	world->Step(1.0f / 60.0f, 6, 2);

	for(b2Contact* c = world->GetContactList(); c; c = c->GetNext())
	{
		if(c->GetFixtureA()->IsSensor() && c->IsTouching())
		{
			PhysBody* pb1 = (PhysBody*)c->GetFixtureA()->GetBody()->GetUserData();
			PhysBody* pb2 = (PhysBody*)c->GetFixtureB()->GetBody()->GetUserData();
			if(pb1 && pb2 && pb1->listener)
				pb1->listener->OnCollision(pb1, pb2);
		}
	}

	return UPDATE_CONTINUE;
}

PhysBody* ModulePhysics::CreateCircle(int x, int y, int radius,b2BodyType btype,int type, bool bullet, float restitution)
{
	b2BodyDef body;
	body.type = btype;
	body.position.Set(PIXEL_TO_METERS(x), PIXEL_TO_METERS(y));

	b2Body* b = world->CreateBody(&body);
	b->SetBullet(bullet);
	b2CircleShape shape;
	shape.m_radius = PIXEL_TO_METERS(radius);
	b2FixtureDef fixture;
	fixture.shape = &shape;
	fixture.density = 10.0f;
    fixture.restitution = restitution;

	b->CreateFixture(&fixture);

	PhysBody* pbody = new PhysBody();
	pbody->body = b;
	b->SetUserData(pbody);
	pbody->width = pbody->height = radius;
	pbody->type = type;

	return pbody;
}

PhysBody* ModulePhysics::CreateRectangle(int x, int y, int width, int height,b2BodyType btype, int type)
{
	b2BodyDef body;
	body.type = btype;
	body.position.Set(PIXEL_TO_METERS(x), PIXEL_TO_METERS(y));

	b2Body* b = world->CreateBody(&body);
	b2PolygonShape box;
	box.SetAsBox(PIXEL_TO_METERS(width) * 0.5f, PIXEL_TO_METERS(height) * 0.5f);

	b2FixtureDef fixture;
	fixture.shape = &box;
	fixture.density = 10.0f;

	b->CreateFixture(&fixture);

	PhysBody* pbody = new PhysBody();
	pbody->body = b;
	b->SetUserData(pbody);
	pbody->width = width * 0.5f;
	pbody->height = height * 0.5f;
	pbody->type = type;

	return pbody;
}

PhysBody* ModulePhysics::CreateRectangleSensor(int x, int y, int width, int height, int type)
{
	b2BodyDef body;
	body.type = b2_staticBody;
	body.position.Set(PIXEL_TO_METERS(x), PIXEL_TO_METERS(y));

	b2Body* b = world->CreateBody(&body);

	b2PolygonShape box;
	box.SetAsBox(PIXEL_TO_METERS(width) * 0.5f, PIXEL_TO_METERS(height) * 0.5f);

	b2FixtureDef fixture;
	fixture.shape = &box;
	fixture.density = 1.0f;
	fixture.isSensor = true;

	b->CreateFixture(&fixture);

	PhysBody* pbody = new PhysBody();
	pbody->body = b;
	pbody->type = type;
	b->SetUserData(pbody);
	pbody->width = width;
	pbody->height = height;

	return pbody;
}

PhysBody* ModulePhysics::CreateChain(int x, int y, int* points, int size, b2BodyType btype,int type, bool open_chain, float restitution)
{
	b2BodyDef body;
	body.type = btype;
	body.position.Set(x, y);

	b2Body* b = world->CreateBody(&body);

	b2ChainShape shape;
	b2Vec2* p = new b2Vec2[size / 2];

	for(uint i = 0; i < size / 2; ++i)
	{
		p[i].x = PIXEL_TO_METERS(points[i * 2 + 0]);
		p[i].y = PIXEL_TO_METERS(points[i * 2 + 1]);
	}

	if (open_chain)
	{
	    shape.CreateChain(p, size / 2);
	}
	else
	{
        shape.CreateLoop(p, size / 2);
	}
	 //Create chain for open shape

	b2FixtureDef fixture;
	fixture.shape = &shape;
	fixture.restitution = restitution;
	b->CreateFixture(&fixture);

	delete p;

	PhysBody* pbody = new PhysBody();
	pbody->body = b;
	pbody->open_chain = open_chain;
	pbody->type = type;
	b->SetUserData(pbody);
	pbody->width = pbody->height = 0;

	return pbody;
}

//
update_status ModulePhysics::PostUpdate()
{
	if(App->input->GetKey(SDL_SCANCODE_F1) == KEY_DOWN)
		debug = !debug;

	if(!debug)
		return UPDATE_CONTINUE;

	b2Body* found_body = nullptr;
	b2Vec2 p(PIXEL_TO_METERS(App->input->GetMouseX()), PIXEL_TO_METERS(App->input->GetMouseY()));

	// Bonus code: this will iterate all objects in the world and draw the circles
	// You need to provide your own macro to translate meters to pixels
	for(b2Body* b = world->GetBodyList(); b; b = b->GetNext())
	{
		for(b2Fixture* f = b->GetFixtureList(); f; f = f->GetNext())
		{
			switch(f->GetType())
			{
				// Draw circles ------------------------------------------------
				case b2Shape::e_circle:
				{
					b2CircleShape* shape = (b2CircleShape*)f->GetShape();
					b2Vec2 pos = f->GetBody()->GetPosition();
					App->renderer->DrawCircle(METERS_TO_PIXELS(pos.x), METERS_TO_PIXELS(pos.y), METERS_TO_PIXELS(shape->m_radius), 255, 255, 255);
				}
				break;

				// Draw polygons ------------------------------------------------
				case b2Shape::e_polygon:
				{
					if (b->IsActive())
					{
						b2PolygonShape* polygonShape = (b2PolygonShape*)f->GetShape();
						int32 count = polygonShape->GetVertexCount();
						b2Vec2 prev, v;

						//Dynamic bodies will be non filled rectangles
						if (!f->IsSensor())
						{
							for(int32 i = 0; i < count; ++i)
							{
								v = b->GetWorldPoint(polygonShape->GetVertex(i));
								if(i > 0)
									App->renderer->DrawLine(METERS_TO_PIXELS(prev.x), METERS_TO_PIXELS(prev.y), METERS_TO_PIXELS(v.x), METERS_TO_PIXELS(v.y), 255, 100, 100);

								prev = v;
							}

							v = b->GetWorldPoint(polygonShape->GetVertex(0));
							App->renderer->DrawLine(METERS_TO_PIXELS(prev.x), METERS_TO_PIXELS(prev.y), METERS_TO_PIXELS(v.x), METERS_TO_PIXELS(v.y), 255, 100, 100);
						}
						//Sensors will be filled rectangles
						else
						{
							PhysBody* b_data = (PhysBody*)b->GetUserData();
							SDL_Rect drawing_rect;
							b_data->GetPosition(drawing_rect.x, drawing_rect.y);
							drawing_rect.w = b_data->width;
							drawing_rect.h = b_data->height;
							if(b_data->alive)
							App->renderer->DrawQuad(drawing_rect, 0, 255, 0,150);
							else
							App->renderer->DrawQuad(drawing_rect, 255, 0, 0, 150);
						}
					}
				}
				break;

				// Draw chains contour -------------------------------------------
				case b2Shape::e_chain:
				{
					if (b->IsActive())
					{
						b2ChainShape* shape = (b2ChainShape*)f->GetShape();
						b2Vec2 prev, v;

						for (int32 i = 0; i < shape->m_count; ++i)
						{
							v = b->GetWorldPoint(shape->m_vertices[i]);
							if (i > 0)
								App->renderer->DrawLine(METERS_TO_PIXELS(prev.x), METERS_TO_PIXELS(prev.y), METERS_TO_PIXELS(v.x), METERS_TO_PIXELS(v.y), 100, 255, 100);
							prev = v;
						}

						PhysBody* chain_data;

						chain_data = (PhysBody*)b->GetUserData();
						if (!chain_data->open_chain)
						{
							v = b->GetWorldPoint(shape->m_vertices[0]);
							App->renderer->DrawLine(METERS_TO_PIXELS(prev.x), METERS_TO_PIXELS(prev.y), METERS_TO_PIXELS(v.x), METERS_TO_PIXELS(v.y), 100, 255, 100);
						}
					}
				}
				break;

				// Draw a single segment(edge) ----------------------------------
				case b2Shape::e_edge:
				{
					b2EdgeShape* shape = (b2EdgeShape*)f->GetShape();
					b2Vec2 v1, v2;

					v1 = b->GetWorldPoint(shape->m_vertex0);
					v1 = b->GetWorldPoint(shape->m_vertex1);
					App->renderer->DrawLine(METERS_TO_PIXELS(v1.x), METERS_TO_PIXELS(v1.y), METERS_TO_PIXELS(v2.x), METERS_TO_PIXELS(v2.y), 100, 100, 255);
				}
				break;
			}

			// TODO 1: If mouse button 1 is pressed ...
			if (App->input->GetMouseButton(SDL_BUTTON_LEFT) == KEY_DOWN)
			{

				const b2Fixture* fixture = b->GetFixtureList();

				while (fixture != NULL)
				{
					if (fixture->GetShape()->TestPoint(b->GetTransform(), p))
					{
						found_body = b;
					}
					fixture = fixture->GetNext();
				}
			}
			// test if the current body contains mouse position
		}
	}

	// If a body was selected we will attach a mouse joint to it
	// so we can pull it around
	// TODO 2: If a body was selected, create a mouse joint
	// using mouse_joint class property

	if (found_body != nullptr)
	{
		b2MouseJointDef def;
		def.bodyA = ground;
		def.bodyB = found_body;
		def.target = p;
		def.dampingRatio = 0.5f;
		def.frequencyHz = 2.0f;
		def.maxForce = 100.0f * found_body->GetMass();

		mouse_joint = (b2MouseJoint*)world->CreateJoint(&def);
	}
	// TODO 3: If the player keeps pressing the mouse button, update
	// target position and draw a red line between both anchor points
	if (App->input->GetMouseButton(SDL_BUTTON_LEFT) == KEY_REPEAT && mouse_joint != nullptr)
	{
		mouse_joint->SetTarget(p);

		App->renderer->DrawLine(METERS_TO_PIXELS(p.x), METERS_TO_PIXELS(p.y), METERS_TO_PIXELS(mouse_joint->GetBodyB()->GetPosition().x), METERS_TO_PIXELS(mouse_joint->GetBodyB()->GetPosition().y), 255, 0, 0);

	}
	// TODO 4: If the player releases the mouse button, destroy the joint
	if (App->input->GetMouseButton(SDL_BUTTON_LEFT) == KEY_UP && mouse_joint != nullptr)
	{
		world->DestroyJoint(mouse_joint);
		mouse_joint = nullptr;
	}

	return UPDATE_CONTINUE;
}

// Called before quitting
bool ModulePhysics::CleanUp()
{
	LOG("Destroying physics world");

	// Delete the whole physics world!
	delete world;

	return true;
}

void PhysBody::GetPosition(int& x, int &y, bool toblit) const
{
	b2Vec2 pos = body->GetPosition();
	if(body->GetFixtureList()->GetType() != b2Shape::e_circle)
	{
		x = METERS_TO_PIXELS(pos.x) - (width/2);
		y = METERS_TO_PIXELS(pos.y) - (height/2);
	}
	else
	{
		x = METERS_TO_PIXELS(pos.x);
		y = METERS_TO_PIXELS(pos.y);
	}
	if (toblit)
	{
		x = METERS_TO_PIXELS(pos.x) - (width);
		y = METERS_TO_PIXELS(pos.y) - (height);
	}

}

float PhysBody::GetRotation() const
{
	return RADTODEG * body->GetAngle();
}

bool PhysBody::Contains(int x, int y) const
{
	b2Vec2 p(PIXEL_TO_METERS(x), PIXEL_TO_METERS(y));

	const b2Fixture* fixture = body->GetFixtureList();

	while(fixture != NULL)
	{
		if(fixture->GetShape()->TestPoint(body->GetTransform(), p) == true)
			return true;
		fixture = fixture->GetNext();
	}

	return false;
}

int PhysBody::RayCast(int x1, int y1, int x2, int y2, float& normal_x, float& normal_y) const
{
	int ret = -1;

	b2RayCastInput input;
	b2RayCastOutput output;

	input.p1.Set(PIXEL_TO_METERS(x1), PIXEL_TO_METERS(y1));
	input.p2.Set(PIXEL_TO_METERS(x2), PIXEL_TO_METERS(y2));
	input.maxFraction = 1.0f;

	const b2Fixture* fixture = body->GetFixtureList();

	while(fixture != NULL)
	{
		if(fixture->GetShape()->RayCast(&output, input, body->GetTransform(), 0) == true)
		{
			// do we want the normal ?

			float fx = x2 - x1;
			float fy = y2 - y1;
			float dist = sqrtf((fx*fx) + (fy*fy));

			normal_x = output.normal.x;
			normal_y = output.normal.y;

			return output.fraction * dist;
		}
		fixture = fixture->GetNext();
	}

	return ret;
}

void ModulePhysics::BeginContact(b2Contact* contact)
{
	PhysBody* physA = (PhysBody*)contact->GetFixtureA()->GetBody()->GetUserData();
	PhysBody* physB = (PhysBody*)contact->GetFixtureB()->GetBody()->GetUserData();

	if(!physA->body->GetFixtureList()->IsSensor() && !physB->body->GetFixtureList()->IsSensor())
	{
		if(physA && physA->listener != NULL)
			physA->listener->OnCollision(physB, physA);

		if(physB && physB->listener != NULL)
			physB->listener->OnCollision(physA, physB);
	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Hawksworth, Syst. Ascom. , Reprint of Volumes 1-4 (1982-1985) 10(2): 132 (1991)

#### Original name
Charcotia rufidula Hue

### Remarks
null


text:
{% include 'widget/tinymce.html' %}
<form method="POST" enctype="multipart/form-data" action="/api/item.rdr">
<input type="hidden" name="redirect_success" value="/ui/list/items.html">

item title:

<input name="itemName" value="" size="66" />

item tags:

<input name="itemTags" value="" size="66" class="taglist">

<input type="checkbox" name="auto_tag" checked /> create any tags that don't already exist

item text:
(add/remove editor)

<textarea name="itemDescription" cols="66" rows="15"></textarea>

file(s) to attach: (optional, one/multiple)

<input type="file" name="itemData">

file type: (optional, browser should populate)

<input name="itemType" value="" size="66">

publication status:

<input type="radio" name="itemStatus" value="inaccessible" /> inaccessible
<input type="radio" name="itemStatus" value="citable" /> citable
<input type="radio" name="itemStatus" value="shareable" checked /> shareable

<input type="checkbox" name="itemIsConsideredPublic" /> safe enough to share in "public" feeds

<input type="submit" name="save" value="create item" />
<input type="reset" name="reset" value="reset form" />
</form>


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

#ifndef ZSTDCB_H
#define ZSTDCB_H

#if defined (__cplusplus)
extern "C" {
#endif

#include <stddef.h>   /* size_t */

#define ZSTDCB_THREAD_MAX 128
#define ZSTDCB_LEVEL_MIN    1
#define ZSTDCB_LEVEL_MAX   22

/* zstd magic values */
#define ZSTDCB_MAGICNUMBER_V01  0x1EB52FFDU
#define ZSTDCB_MAGICNUMBER_MIN  0xFD2FB522U
#define ZSTDCB_MAGICNUMBER_MAX  0xFD2FB528U
#define ZSTDCB_MAGIC_SKIPPABLE  0x184D2A50U

/* **************************************
 * Error Handling
 ****************************************/

typedef enum {
  ZSTDCB_error_no_error,
  ZSTDCB_error_memory_allocation,
  ZSTDCB_error_init_missing,
  ZSTDCB_error_read_fail,
  ZSTDCB_error_write_fail,
  ZSTDCB_error_data_error,
  ZSTDCB_error_frame_compress,
  ZSTDCB_error_frame_decompress,
  ZSTDCB_error_compressionParameter_unsupported,
  ZSTDCB_error_compression_library,
  ZSTDCB_error_canceled,
  ZSTDCB_error_maxCode
} ZSTDCB_ErrorCode;

extern size_t zstdmt_errcode;

#define ZSTDCB_PREFIX(name) ZSTDCB_error_##name
#define ZSTDCB_ERROR(name) ((size_t)-ZSTDCB_PREFIX(name))
extern unsigned ZSTDCB_isError(size_t code);
extern const char* ZSTDCB_getErrorString(size_t code);

/* **************************************
 * Structures
 ****************************************/

typedef struct {
	void *buf;		/* ptr to data */
	size_t size;		/* current filled in buf */
	size_t allocated;	/* length of buf */
} ZSTDCB_Buffer;

/**
 * reading and writing functions
 * - you can use stdio functions or plain read/write
 * - just write some wrapper on your own
 * - a sample is given in 7-Zip ZS
 *
 * error definitions:
 *  0 = success
 * -1 = generic read/write error
 * -2 = user abort
 * -3 = memory
 */
typedef int (fn_read) (void *args, ZSTDCB_Buffer * in);
typedef int (fn_write) (void *args, ZSTDCB_Buffer * out);

typedef struct {
	fn_read *fn_read;
	void *arg_read;
	fn_write *fn_write;
	void *arg_write;
} ZSTDCB_RdWr_t;

/* **************************************
 * Compression
 ****************************************/

typedef struct ZSTDCB_CCtx_s ZSTDCB_CCtx;

/**
 * ZSTDCB_createCCtx() - allocate new compression context
 *
 * This function allocates and initializes an zstd commpression context.
 * The context can be used multiple times without the need for resetting
 * or re-initializing.
 *
 * @level: compression level, which should be used (1..22)
 * @threads: number of threads, which should be used (1..ZSTDCB_THREAD_MAX)
 * @inputsize: - if zero, becomes some optimal value for the level
 *             - if nonzero, the given value is taken
 * @zstdmt_errcode: space for storing zstd errors (needed for thread safety)
 * @return: the context on success, zero on error
 */
ZSTDCB_CCtx *ZSTDCB_createCCtx(int threads, int level, int inputsize);

/**
 * ZSTDCB_compressDCtx() - threaded compression for zstd
 *
 * This function will create valid zstd streams. The number of threads,
 * the input chunksize and the compression level are ....
 *
 * @ctx: context, which needs to be created with ZSTDCB_createDCtx()
 * @rdwr: callback structure, which defines reding/writing functions
 * @return: zero on success, or error code
 */
size_t ZSTDCB_compressCCtx(ZSTDCB_CCtx * ctx, ZSTDCB_RdWr_t * rdwr);

/**
 * ZSTDCB_GetFramesCCtx() - number of written frames
 * ZSTDCB_GetInsizeCCtx() - read bytes of input
 * ZSTDCB_GetOutsizeCCtx() - written bytes of output
 *
 * These three functions will return some statistical data of the
 * compression context ctx.
 *
 * @ctx: context, which should be examined
 * @return: the request value, or zero on error
 */
size_t ZSTDCB_GetFramesCCtx(ZSTDCB_CCtx * ctx);
size_t ZSTDCB_GetInsizeCCtx(ZSTDCB_CCtx * ctx);
size_t ZSTDCB_GetOutsizeCCtx(ZSTDCB_CCtx * ctx);

/**
 * ZSTDCB_freeCCtx() - free compression context
 *
 * This function will free all allocated resources, which were allocated
 * by ZSTDCB_createCCtx(). This function can not fail.
 *
 * @ctx: context, which should be freed
 */
void ZSTDCB_freeCCtx(ZSTDCB_CCtx * ctx);

/* **************************************
 * Decompression
 ****************************************/

typedef struct ZSTDCB_DCtx_s ZSTDCB_DCtx;

/**
 * 1) allocate new cctx
 * - return cctx or zero on error
 *
 * @level   - 1 .. 22
 * @threads - 1 .. ZSTDCB_THREAD_MAX
 * @srclen  - the max size of src for ZSTDCB_compressCCtx()
 * @dstlen  - the min size of dst
 */
ZSTDCB_DCtx *ZSTDCB_createDCtx(int threads, int inputsize);

/**
 * ZSTDCB_decompressDCtx() - threaded decompression for zstd
 *
 * This function will decompress valid zstd streams.
 *
 * @ctx: context, which needs to be created with ZSTDCB_createDCtx()
 * @rdwr: callback structure, which defines reding/writing functions
 * @return: zero on success, or error code
 */
size_t ZSTDCB_decompressDCtx(ZSTDCB_DCtx * ctx, ZSTDCB_RdWr_t * rdwr);

/**
 * ZSTDCB_GetFramesDCtx() - number of read frames
 * ZSTDCB_GetInsizeDCtx() - read bytes of input
 * ZSTDCB_GetOutsizeDCtx() - written bytes of output
 *
 * These three functions will return some statistical data of the
 * decompression context ctx.
 *
 * @ctx: context, which should be examined
 * @return: the request value, or zero on error
 */
size_t ZSTDCB_GetFramesDCtx(ZSTDCB_DCtx * ctx);
size_t ZSTDCB_GetInsizeDCtx(ZSTDCB_DCtx * ctx);
size_t ZSTDCB_GetOutsizeDCtx(ZSTDCB_DCtx * ctx);

/**
 * ZSTDCB_freeDCtx() - free decompression context
 *
 * This function will free all allocated resources, which were allocated
 * by ZSTDCB_createDCtx(). This function can not fail.
 *
 * @ctx: context, which should be freed
 */
void ZSTDCB_freeDCtx(ZSTDCB_DCtx * ctx);

#if defined (__cplusplus)
}
#endif
#endif				/* ZSTDCB_H */


text: print('bar.js is loaded');


text:
#ifndef SYNOP_GMAC_HOST_H
#define SYNOP_GMAC_HOST_H 1

/*
#include <linux/pci.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
*/

#include "synopGMAC_plat.h"
//#include "synopGMAC_pci_bus_interface.h"
#include "synopGMAC_Dev.h"
#include "mii.h"

//#define ENH_DESC
//#define ENH_DESC_8W

struct net_device_stats
{
	unsigned long	rx_packets;		/* total packets received	*/
	unsigned long	tx_packets;		/* total packets transmitted	*/
	unsigned long	rx_bytes;		/* total bytes received 	*/
	unsigned long	tx_bytes;		/* total bytes transmitted	*/
	unsigned long	rx_errors;		/* bad packets received		*/
	unsigned long	tx_errors;		/* packet transmit problems	*/
	unsigned long	rx_dropped;		/* no space in linux buffers	*/
	unsigned long	tx_dropped;		/* no space available in linux	*/
	unsigned long	multicast;		/* multicast packets received	*/
	unsigned long	collisions;

	/* detailed rx_errors: */
	unsigned long	rx_length_errors;
	unsigned long	rx_over_errors;		/* receiver ring buff overflow	*/
	unsigned long	rx_crc_errors;		/* recved pkt with crc error	*/
	unsigned long	rx_frame_errors;	/* recv'd frame alignment error */
	unsigned long	rx_fifo_errors;		/* recv'r fifo overrun		*/
	unsigned long	rx_missed_errors;	/* receiver missed packet	*/

	/* detailed tx_errors */
	unsigned long	tx_aborted_errors;
	unsigned long	tx_carrier_errors;
	unsigned long	tx_fifo_errors;
	unsigned long	tx_heartbeat_errors;
	unsigned long	tx_window_errors;

	/* for cslip etc */
	unsigned long	rx_compressed;
	unsigned long	tx_compressed;
};

/*
struct	PmonInet{
	struct device sc_dev;
	void *sc_ih;

	struct arpcom arpcom;

//	struct mii_data sc_mii;		// MII media information
	char  dev_addr[6]; //the net interface's address
	unsigned long ioaddr;

//	int flags;
//	int mc_count;

};
*/

//typedef struct synopGMACAdapterStruct{
#if 0
struct synopGMACAdapterStruct{

/*Device Dependent Data structur*/
struct synopGMACdevice * synopGMACdev;

/*Os/Platform Dependent Data Structures*/
//struct pci_dev * synopGMACpcidev;

//struct net_device *synopGMACnetdev;

struct net_device_stats synopGMACNetStats;
//u32 synopGMACPciState[16];

struct PmonInet * PInetdev;

//} synopGMACPciNetworkAdapter;
}synopGMACNetworkAdapter;
#endif
typedef struct synopGMACNetworkAdapter{

/*Device Dependent Data structur*/
synopGMACdevice * synopGMACdev;

/*Os/Platform Dependent Data Structures*/
//struct pci_dev * synopGMACpcidev;

//struct net_device *synopGMACnetdev;

struct net_device_stats synopGMACNetStats;
//u32 synopGMACPciState[16];

//struct PmonInet * PInetdev;

struct mii_if_info mii;
} synopGMACPciNetworkAdapter;

/*
static struct mbuf * getmbuf(struct synopGMACNetworkAdapter * tp)
{
	struct mbuf *m;
//	struct PomnInet * tp = adapter->PInetDev;

	MGETHDR(m, M_DONTWAIT, MT_DATA);
	if(m == NULL){
		printf("getmbuf failed, Out of memory!!!\n");
		return  NULL;
	} else {
		MCLGET(m, M_DONTWAIT);
		if ((m->m_flags & M_EXT) == 0) {
			m_freem(m);
			return NULL;
		}
		if(m->m_data != m->m_ext.ext_buf){
			printf("m_data not equal to ext_buf!!!\n");
		}
	}

#if defined(__mips__)

//	pci_sync_cache(tp->sc_pc, (vm_offset_t)tp->tx_buffer[entry], len, SYNC_W);

	;
#define RFA_ALIGNMENT_FUDGE 2
	m->m_data += RFA_ALIGNMENT_FUDGE;
#else
	m->m_data += RFA_ALIGNMENT_FUDGE;
#endif
	return m;
}
*/

#endif


text:
dir=$(dirname "$0")

mkdir -p $dir/toolchain/build/

cd $dir/toolchain/build/

# Accept an optional command line parameter to set the build type.
# Valid build types are Debug, Release, RelWithDebInfo, MinSizeRel
if [ -z "$1" ]; then
	cmake -DCMAKE_BUILD_TYPE=$1 -DCC0_USE_STATIC_CRT=1 ..
else
	cmake -DCC0_USE_STATIC_CRT=1
fi

# make VERBOSE=1
make

cd -


text:
package com.xiaogua.better.class_init;

public class Super_Base_Class {
	static {
		System.out.println("super static code block");
		c = '0';
	}

	protected static char c = '1';

	{
		System.out.println("super before normal code block, c=" + c);
		c = '2';
	}

	public Super_Base_Class() {
		System.out.println("super before constructor,c=" + c);
		c = '3';
	}

	{
		System.out.println("super before normal code block, c=" + c);
		c = '4';
	}

	static {
		System.out.println("super static code block 2,c="+c);
		c = '5';
	}
}


text:
package org.sagebionetworks.repo.model.table;

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

import org.junit.Test;

public class TableConstantsTest {
	@Test
	public void testIsReservedColumnNameNegative(){
		assertFalse(TableConstants.isReservedColumnName("notReserved"));
	}

	@Test
	public void testIsReservedColumnNameNull(){
		assertFalse(TableConstants.isReservedColumnName(null));
	}

	@Test
	public void testIsReservedColumnNameRowIdCaseInsensitive(){
		assertTrue("The isReservedColumnName() method should be case insensitive.", TableConstants.isReservedColumnName("row_id"));
	}

	@Test
	public void testIsReservedColumnNameRowVersion(){
		assertTrue(TableConstants.isReservedColumnName("ROW_VERSION"));
	}
}


text:
package com.rao.loveyou.presenter.activity;

/**
 * @auther rjl
 * @time 2017/9/11.
 * @descr
 */

public interface RegisterPresenter {

    void register(String userName, String passWord);
    void getVerificationCode();

}


text:
<?php

namespace PhpSsrs\ReportingService2005;

class ListSchedules
{

  /**
   *
   * @access public
   */
  public function __construct()
  {

  }

}


text:
package de.codecentric.boot.admin.server.ui.web;

import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;

public class HomepageForwardingMatcher<T> implements Predicate<T> {

	private final List<Pattern> includeRoutes;

	private final List<Pattern> excludeRoutes;

	private final Function<T, String> methodAccessor;

	private final Function<T, String> pathAccessor;

	private final Function<T, List<MediaType>> acceptsAccessor;

	public HomepageForwardingMatcher(List<String> includeRoutes, List<String> excludeRoutes,
			Function<T, String> methodAccessor, Function<T, String> pathAccessor,
			Function<T, List<MediaType>> acceptsAccessor) {
		this.includeRoutes = toPatterns(includeRoutes);
		this.excludeRoutes = toPatterns(excludeRoutes);
		this.methodAccessor = methodAccessor;
		this.pathAccessor = pathAccessor;
		this.acceptsAccessor = acceptsAccessor;
	}

	public boolean test(T request) {
		if (!HttpMethod.GET.matches(this.methodAccessor.apply(request))) {
			return false;
		}

		String path = this.pathAccessor.apply(request);
		boolean isExcludedRoute = this.excludeRoutes.stream().anyMatch((p) -> p.matcher(path).matches());
		boolean isIncludedRoute = this.includeRoutes.stream().anyMatch((p) -> p.matcher(path).matches());
		if (isExcludedRoute || !isIncludedRoute) {
			return false;
		}

		return this.acceptsAccessor.apply(request).stream().anyMatch((t) -> t.includes(MediaType.TEXT_HTML));
	}

	private List<Pattern> toPatterns(List<String> routes) {
		return routes.stream().map((r) -> "^" + r.replaceAll("/[*][*]", "(/.*)?").replaceAll("/[*]/", "/[^/]+/") + "$")
				.map(Pattern::compile).collect(Collectors.toList());
	}

}


text:
namespace ICG.Modules.DnnQuiz.Components.InfoObjects
{
    /// <summary>
    ///     This class holds information about the quiz for a given week
    /// </summary>
    public class QuizInfo
    {
        #region Public Properties

        /// <summary>
        ///     Gets or sets the quiz id.
        /// </summary>
        /// <value>The quiz id.</value>
        public int QuizId { get; set; }

        /// <summary>
        ///     Gets or sets the module id.
        /// </summary>
        /// <value>The module id.</value>
        public int ModuleId { get; set; }

        /// <summary>
        ///     Gets or sets the quiz title.
        /// </summary>
        /// <value>The quiz title.</value>
        public string QuizTitle { get; set; }

        /// <summary>
        ///     Gets or sets the name of the role.
        /// </summary>
        /// <value>The name of the role.</value>
        public string RoleName { get; set; }

        public int EmailResultsMode { get; set; }
        public string CertificateTemplatePath { get; set; }

        /// <summary>
        ///     Gets or sets the role id.
        /// </summary>
        /// <value>The role id.</value>
        public int RoleId { get; set; }

        /// <summary>
        ///     Gets or sets the pass percentage.
        /// </summary>
        /// <value>The pass percentage.</value>
        public decimal PassPercentage { get; set; }

        /// <summary>
        ///     Gets or sets a value indicating whether this instance is published.
        /// </summary>
        /// <value>
        ///     <c>true</c> if this instance is published; otherwise, <c>false</c>.
        /// </value>
        public bool IsPublished { get; set; }

        /// <summary>
        ///     Gets or sets a value indicating whether this instance can expire.
        /// </summary>
        /// <value>
        ///     <c>true</c> if this instance can expire; otherwise, <c>false</c>.
        /// </value>
        public bool CanExpire { get; set; }

        /// <summary>
        ///     Gets or sets the duration of the expire.
        /// </summary>
        /// <value>The duration of the expire.</value>
        public int ExpireDuration { get; set; }

        /// <summary>
        ///     Gets or sets the role to add.
        /// </summary>
        /// <value>The role to add.</value>
        public string RoleToAdd { get; set; }

        /// <summary>
        ///     Gets or sets a value indicating whether [allow retake].
        /// </summary>
        /// <value>
        ///     <c>true</c> if [allow retake]; otherwise, <c>false</c>.
        /// </value>
        public bool AllowRetake { get; set; }

        #endregion
    }
}


text:
package tlc2.tool;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

import tlc2.output.EC;
import tlc2.output.EC.ExitStatus;
import tlc2.tool.liveness.ModelCheckerTestCase;

public class FingerprintExceptionNextCallstackTest extends ModelCheckerTestCase {

	public FingerprintExceptionNextCallstackTest() {
		super("FingerprintExceptionNextCallstack", new String[] { "-config", "FingerprintExceptionNext.cfg" },
				ExitStatus.FAILURE_SPEC_EVAL);
	}

	@Test
	public void testSpec() {
		// ModelChecker has finished with a general exception, a fingerprint exception and underlying overflow exception
		assertTrue(recorder.recorded(EC.TLC_FINISHED));
		assertTrue(recorder.recordedWithStringValues(EC.TLC_STATS, "1", "1", "0"));
		assertTrue(recorder.recordedWithStringValue(EC.TLC_INIT_GENERATED1, "1"));
		assertTrue(recorder.recorded(EC.GENERAL));
		String arg1 = "0. Line 9, column 9 to line 9, column 19 in FingerprintExceptionNextCallstack\n"
				+ "1. Line 9, column 14 to line 9, column 19 in FingerprintExceptionNextCallstack\n"
				+ "2. Line 7, column 10 to line 7, column 49 in FingerprintExceptionNextCallstack\n"
				+ "3. Line 7, column 43 to line 7, column 49 in FingerprintExceptionNextCallstack\n"
				+ "4. Line 7, column 25 to line 7, column 32 in FingerprintExceptionNextCallstack\n\n";
		String arg2 = "Attempted to check if the non-enumerable value\n"
				+ "42\n"
				+ "is element of\n"
				+ "SUBSET 42";
		assertTrue(recorder.recordedWithStringValues(EC.TLC_FINGERPRINT_EXCEPTION, arg1, arg2));
	}
}


text:
import geoblaze from 'geoblaze';
import BaseStats from '../base-stats';
import ModeComponent from './mode.component';
import { withProps } from 'recompose';

const calculateMode = (raster, coors) => {
  const modes = geoblaze.mode(raster, coors);
  return modes.map(band => {
    if (typeof band === 'number') return band;
    return band.join(", ");
  });
}

const ModeContainer = withProps(
  { func: calculateMode }
)(BaseStats(ModeComponent));

export default ModeContainer;


text:
function P = doscon_p(doscon_file);
%  P = doscon_p(doscon_file)
%   Parameter initialisation of model doscon
%   P   Parameter list
%
% Stimela, 2004

% © Kim van Schagen,

%Check if given file exists
doscon_fileEcht = chckFile(doscon_file);
if ~doscon_fileEcht
    error(['Cannot find parameterfile ''' doscon_file ''' .']);
else
  %Get Parameter data (evaluate entries, and limits) and return real data
  P = st_getPdata(doscon_fileEcht, 'doscon');
end

%%% MODEL-SPECIFIC => %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Fill parameter list with precalculated parameters
% eg. P.CalData = P.Ex1*P.Ex2;

%%% <= MODEL-SPECIFIC %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


text:
package org.opensingular.requirement.module.admin.healthsystem.docs.presentation;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.opensingular.requirement.module.admin.healthsystem.docs.DocBlock;
import org.opensingular.requirement.module.admin.healthsystem.docs.DocFieldMetadata;
import org.opensingular.requirement.module.admin.healthsystem.docs.DocTable;

public class DefaultDocumentationDefinition implements DocumentationDefinition {

    @Override
    public FormDocumentationRenderer getRenderer() {
        return new DefaultFormDocumentationRenderer();
    }

    @Override
    public List<FormDocumentationColumnRenderer> getColumns() {
        List<FormDocumentationColumnRenderer> columns = new ArrayList<>();
        columns.add(newNumberPerTableColumnRenderer());
        columns.add(new DefaultFormDocumentationColumnRenderer("Nome do Campo", DocFieldMetadata.DocFieldValue.FIELD_NAME));
        columns.add(new DefaultFormDocumentationColumnRenderer("Tipo", DocFieldMetadata.DocFieldValue.HTML_COMPONENT_TYPE));
        columns.add(newAlternativeColumnRenderer("Obrigatório", getEnablingRuleConverter(DocFieldMetadata.DocFieldValue.HAS_REQUIRED_RULE), DocFieldMetadata.DocFieldValue.HAS_REQUIRED_RULE, DocFieldMetadata.DocFieldValue.REQUIRED));
        columns.add(newAlternativeColumnRenderer("Habilitado", getEnablingRuleConverter(DocFieldMetadata.DocFieldValue.HAS_ENABLING_RULE), DocFieldMetadata.DocFieldValue.HAS_ENABLING_RULE, DocFieldMetadata.DocFieldValue.ENABLED));
        columns.add(newAlternativeColumnRenderer("Tamanho", getFieldSizeConverter(), DocFieldMetadata.DocFieldValue.MAX_UPLOAD_SIZE_IN_BYTES, DocFieldMetadata.DocFieldValue.FIELD_LENGTH));
        columns.add(new DefaultFormDocumentationColumnRenderer("Regras", DocFieldMetadata.DocFieldValue.HAS_ENABLING_RULE, DocFieldMetadata.DocFieldValue.HAS_REQUIRED_RULE, DocFieldMetadata.DocFieldValue.HAS_UPDATE_LISTENER, DocFieldMetadata.DocFieldValue.HAS_VISIBILITY_RULE));
        columns.add(new DefaultFormDocumentationColumnRenderer("Mensagens", DocFieldMetadata.DocFieldValue.HAS_VALIDATION_RULE));
        columns.add(new DefaultFormDocumentationColumnRenderer("Domínio / Máscara / Hint / Demais observações", DocFieldMetadata.DocFieldValue.ENUM_SELECTION_OPTIONS, DocFieldMetadata.DocFieldValue.MASK, DocFieldMetadata.DocFieldValue.FIELD_SUBTITLE, DocFieldMetadata.DocFieldValue.DEPENDENT_STYPES_FIELDS_NAME, DocFieldMetadata.DocFieldValue.MAX_SIZE, DocFieldMetadata.DocFieldValue.MIN_SIZE));
        return columns;
    }

    private FormFieldValueConverter getEnablingRuleConverter(DocFieldMetadata.DocFieldValue<?> toOverride) {
        return new DefaultValueConverter() {
            @Override
            public String format(DocFieldMetadata.DocFieldValue<?> fieldValue, Object value) {
                if (fieldValue.equals(toOverride)) {
                    if ((Boolean)value) {
                        return "Sim";
                    }
                }
                return MessagesValueConverter.getDefault().format(fieldValue, value);
            }
        };
    }

    private FormDocumentationColumnRenderer newNumberPerTableColumnRenderer() {
        return new DefaultFormDocumentationColumnRenderer("Número") {
            private Map<DocTable, Integer> map = new HashMap<>();

            @Override
            public String renderColumn(DocTable table, DocBlock block, DocFieldMetadata fieldMetadata) {
                map.putIfAbsent(table, 1);
                int count = map.get(table);
                if (fieldMetadata != null) {
                    map.put(table, count + 1);
                    return String.valueOf(count);
                } else {
                    return block.getBlockName();
                }
            }
        };
    }

    private FormDocumentationColumnRenderer newAlternativeColumnRenderer(String label, FormFieldValueConverter converter, DocFieldMetadata.DocFieldValue<?> mainValue, DocFieldMetadata.DocFieldValue<?> secondaryValue) {
        return new DefaultFormDocumentationColumnRenderer(label, converter, mainValue, secondaryValue) {
            @Override
            public String renderColumn(DocTable table, DocBlock block, DocFieldMetadata fieldMetadata) {
                String result = null;
                if (fieldMetadata.getValue(mainValue) != null) {
                    result = StringUtils.defaultString(getConverter().format(mainValue, fieldMetadata.getValue(mainValue)), "");
                }
                if (StringUtils.isBlank(result)) {
                    result = StringUtils.defaultString(getConverter().format(secondaryValue, fieldMetadata.getValue(secondaryValue)), "");
                }
                return result;
            }
        };
    }

    private FormFieldValueConverter getFieldSizeConverter() {
        return new DefaultValueConverter() {
            @Override
            public String format(DocFieldMetadata.DocFieldValue<?> fieldValue, Object value) {
                String result;
                if (fieldValue.equals(DocFieldMetadata.DocFieldValue.MAX_UPLOAD_SIZE_IN_BYTES) && value != null) {
                    result = (Long) value / (1024 * 1024) + "MB";
                } else {
                    result = super.format(fieldValue, value);
                }
                if (StringUtils.isBlank(result)) {
                    result = "N/A";
                }
                return result;
            }
        };
    }

}


text:
<!DOCTYPE HTML>
<html>
<head>
<title>Testcase for bug 776265</title>
<style type="text/css">
textarea {
    float: left;
    height: 40px;
    width: 40px;
    border: 1px solid #aaa;
    padding: 4px;
}
</style>
</head>
<body><textarea></textarea>
</body>
</html>


text:
package com.htmlhifive.testexplorer.entity;

import java.io.IOException;

import org.junit.Assert;
import org.junit.Test;

public class ScreenshotTest {
	@Test
	public void testGetterSetter() throws ClassNotFoundException, IOException
	{
		Screenshot s = new Screenshot();
		Screenshot s2 = new Screenshot();
		TestEnvironment tenv = new TestEnvironment();

		s.setId(7357);
		s.setExpectedScreenshot(s2);
		s.setFileName("TEST FILE NAME");
		s.setComparisonResult(true);
		s.setTestClass("TEST CLASS");
		s.setTestMethod("TEST METHOD");
		s.setTestScreen("TEST SCREEN");
		s.setTestExecutionId(111);
		s.setTestEnvironment(tenv);

		Assert.assertEquals(7357, s.getId().intValue());
		Assert.assertEquals(s2, s.getExpectedScreenshot());
		Assert.assertEquals("TEST FILE NAME", s.getFileName());
		Assert.assertEquals(true, s.getComparisonResult());
		Assert.assertEquals("TEST CLASS", s.getTestClass());
		Assert.assertEquals("TEST METHOD", s.getTestMethod());
		Assert.assertEquals("TEST SCREEN", s.getTestScreen());
		Assert.assertEquals(111, s.getTestExecutionId().intValue());
		Assert.assertEquals(tenv, s.getTestEnvironment());

		s = (Screenshot)new SerializeTestUtil().serializeAndDeserialize(s);

		Assert.assertEquals(7357, s.getId().intValue());
		Assert.assertEquals("TEST FILE NAME", s.getFileName());
		Assert.assertEquals(true, s.getComparisonResult());
		Assert.assertEquals("TEST CLASS", s.getTestClass());
		Assert.assertEquals("TEST METHOD", s.getTestMethod());
		Assert.assertEquals("TEST SCREEN", s.getTestScreen());
	}
}


text:
require 'win-ffi/user32/enum/window/control/button/button_state'
require 'win-ffi/user32/enum/window/control/button/button_message'

require 'win-ffi-wrapper/window/control/button_state'

module WinFFIWrapper
  class Window
    def add_checkbox(button)
      raise ArgumentError unless button.is_a?(CheckBox)
      add_control(button)
    end
  end

  class CheckBox < Button
    include ButtonState

    bindable :text,
             default: 'CheckBox'

    bindable :alignment,
             default: :left

    bindable :text_position,
             default: :right,
             validate: [:right, :left]

    def is_checked?
      get_check == :CHECKED
    end

    def is_unchecked?
      get_check == :UNCHECKED
    end

    def is_indeterminate?
      get_check == :INDETERMINATE
    end

    alias_method :checked?, :is_checked?
    alias_method :unchecked?, :is_unchecked?
    alias_method :indeterminate?, :is_indeterminate?

    private
    def create_window_style
      style = [
          has_indeterminate_state ? :AUTO3STATE : :AUTOCHECKBOX,
          text_position == :left ? :LEFT_TEXT : false
      ].select { |flag| flag }
      style.map { |v| User32::ButtonStyle[v] }.reduce(0, &:|) | super
    end
  end
end


text:
package org.jetbrains.idea.svn.dialogs;

import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.changes.TransparentlyFailedValue;
import com.intellij.openapi.vcs.changes.TransparentlyFailedValueI;
import com.intellij.openapi.vcs.persistent.SmallMapSerializer;
import com.intellij.util.Consumer;
import com.intellij.util.ThrowableConvertor;
import com.intellij.util.ValueHolder;
import com.intellij.util.containers.MultiMap;
import com.intellij.util.continuation.TaskDescriptor;
import com.intellij.util.io.DataExternalizer;
import com.intellij.util.io.EnumeratorStringDescriptor;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.svn.SvnVcs;
import org.jetbrains.idea.svn.history.CopyData;
import org.jetbrains.idea.svn.history.FirstInBranch;
import org.tmatesoft.svn.core.SVNException;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.File;
import java.io.IOException;
import java.util.*;

public class SvnBranchPointsCalculator {
  private static final Logger LOG = Logger.getInstance("#org.jetbrains.idea.svn.dialogs.SvnBranchPointsCalculator");
  private FactsCalculator<KeyData, WrapperInvertor<BranchCopyData>, SVNException> myCalculator;
  private PersistentHolder myPersistentHolder;
  private File myFile;
  private final Project myProject;

  public SvnBranchPointsCalculator(final Project project) {
    myProject = project;
    final File vcs = new File(PathManager.getSystemPath(), "vcs");
    File file = new File(vcs, "svn_copy_sources");
    file.mkdirs();
    myFile = file;
    myFile = new File(file, project.getLocationHash());
  }

  public void activate() {
    ValueHolder<WrapperInvertor<BranchCopyData>, KeyData> cache = null;

    myPersistentHolder = new PersistentHolder(myFile);
    cache = new ValueHolder<WrapperInvertor<BranchCopyData>, KeyData>() {
      public WrapperInvertor<BranchCopyData> getValue(KeyData dataHolder) {
        final WrapperInvertor<BranchCopyData> result =
          myPersistentHolder.getBestHit(dataHolder.getRepoUrl(), dataHolder.getSourceUrl(), dataHolder.getTargetUrl());
        if (LOG.isDebugEnabled()) {
          LOG.debug("Persistent for: " + dataHolder.toString() + " returned: " + (result == null ? null : result.toString()));
        }
        return result;
      }
      public void setValue(WrapperInvertor<BranchCopyData> value, KeyData dataHolder) {
        if (LOG.isDebugEnabled()) {
          LOG.debug("Put into persistent: key: " + dataHolder.toString() + " value: " + value.toString());
        }
        myPersistentHolder.put(dataHolder.getRepoUrl(), value.getWrapped().getTarget(), value.getWrapped());
      }
    };

    myCalculator = new FactsCalculator<KeyData, WrapperInvertor<BranchCopyData>, SVNException>(
      myProject, "Looking for branch origin", cache, new Loader(myProject));
  }

  public void deactivate() {
    myPersistentHolder.close();
    myCalculator = null;
    myPersistentHolder = null;
  }

  private static class BranchDataExternalizer implements DataExternalizer<TreeMap<String,BranchCopyData>> {
    public void save(DataOutput out, TreeMap<String,BranchCopyData> value) throws IOException {
      out.writeInt(value.size());
      for (Map.Entry<String, BranchCopyData> entry : value.entrySet()) {
        out.writeUTF(entry.getKey());
        final BranchCopyData entryValue = entry.getValue();
        out.writeUTF(entryValue.getSource());
        out.writeUTF(entryValue.getTarget());
        out.writeLong(entryValue.getSourceRevision());
        out.writeLong(entryValue.getTargetRevision());
      }
    }

    public TreeMap<String,BranchCopyData> read(DataInput in) throws IOException {
      final TreeMap<String,BranchCopyData> result = new TreeMap<String, BranchCopyData>();

      final int num = in.readInt();
      for (int i = 0; i < num; i++) {
        final String key = in.readUTF();
        final String source = in.readUTF();
        final String target = in.readUTF();
        final long sourceRevision = in.readLong();
        final long targetRevision = in.readLong();

        result.put(key, new BranchCopyData(source, sourceRevision, target, targetRevision));
      }
      return result;
    }
  }

  public static class WrapperInvertor<T extends Invertor<T>> {
    private final T myWrapped;
    private final boolean myInvertedSense;

    public WrapperInvertor(boolean invertedSense, T wrapped) {
      myInvertedSense = invertedSense;
      myWrapped = wrapped;
    }

    public boolean isInvertedSense() {
      return myInvertedSense;
    }

    public T getWrapped() {
      return myWrapped;
    }

    public T getTrue() {
      return myInvertedSense ? myWrapped.invertSelf() : myWrapped;
    }

    public T inverted() {
      return myWrapped.invertSelf();
    }

    @Override
    public String toString() {
      return "inverted: " + myInvertedSense + " wrapped: " + myWrapped.toString();
    }
  }

  private static class PersistentHolder {
    private final SmallMapSerializer<String, TreeMap<String, BranchCopyData>> myPersistentMap;
    private final MultiMap<String, String> myForSearchMap;
    private final Object myLock;

    PersistentHolder(final File file) {
      myLock = new Object();
      myPersistentMap = new SmallMapSerializer<String, TreeMap<String, BranchCopyData>>(
        file, new EnumeratorStringDescriptor(), new BranchDataExternalizer());
      // list for values by default
      myForSearchMap = new MultiMap<String, String>();
      for (String s : myPersistentMap.keySet()) {
        final TreeMap<String, BranchCopyData> map = myPersistentMap.get(s);
        if (map != null) {
          myForSearchMap.put(s, new ArrayList<String>(map.keySet()));
        }
      }

      for (String key : myForSearchMap.keySet()) {
        Collections.sort((List<String>) myForSearchMap.get(key));
      }
    }

    public void close() {
      myPersistentMap.force();
    }

    public void put(final String uid, final String target, final BranchCopyData data) {
      // todo - rewrite of rather big piece; consider rewriting
      synchronized (myLock) {
        TreeMap<String, BranchCopyData> map = myPersistentMap.get(uid);
        if (map == null) {
          map = new TreeMap<String, BranchCopyData>();
        }
        map.put(target, data);
        myPersistentMap.put(uid, map);
        if (myForSearchMap.containsKey(uid)) {
          final List<String> list = (List<String>)myForSearchMap.get(uid);
          final int idx = Collections.binarySearch(list, target);
          if (idx < 0) {
            final int insertionIdx = - idx - 1;
            list.add(insertionIdx, target);
          }
        } else {
          myForSearchMap.putValue(uid, target);
        }
      }
      myPersistentMap.force();
    }

    @Nullable
    public WrapperInvertor<BranchCopyData> getBestHit(final String repoUrl, final String source, final String target) {
      final List<String> keys;
      synchronized (myLock) {
        keys = (List<String>) myForSearchMap.get(repoUrl);
      }
      // keys are never removed, so we can use 2 synchronized blocks
      final String sourceMatching = getMatchingUrl(keys, source);
      final String targetMatching = getMatchingUrl(keys, target);

      if (sourceMatching == null && targetMatching == null) return null;

      synchronized (myLock) {
        final TreeMap<String, BranchCopyData> map = myPersistentMap.get(repoUrl);

        final boolean sourceIsOut = sourceMatching == null;
        if (sourceIsOut || targetMatching == null) {
          // if found by "target" url - we correctly thought that target of copy is target
          return sourceIsOut ? new WrapperInvertor<BranchCopyData>(false, map.get(targetMatching)) :
                 new WrapperInvertor<BranchCopyData>(true, map.get(sourceMatching));
        }
        final BranchCopyData sourceData = map.get(sourceMatching);
        final BranchCopyData targetData = map.get(targetMatching);

        final boolean inverted = sourceData.getTargetRevision() > targetData.getTargetRevision();
        return new WrapperInvertor<BranchCopyData>(inverted, inverted ? sourceData : targetData);
      }
    }

    @Nullable
    private String getMatchingUrl(List<String> keys, String source) {
      final int idx = Collections.binarySearch(keys, source);
      if (idx >= 0) return keys.get(idx);
      final int beforeInsertionIdx = - idx - 2;
      if (beforeInsertionIdx < 0) return null;
      final String candidate = keys.get(beforeInsertionIdx);
      if (source.startsWith(candidate)) return candidate;
      return null;
    }
  }

  private static class Loader implements ThrowableConvertor<KeyData, WrapperInvertor<BranchCopyData>, SVNException> {
    private SvnVcs myVcs;

    private Loader(final Project project) {
      myVcs = SvnVcs.getInstance(project);
    }

    @Override
    public WrapperInvertor<BranchCopyData> convert(final KeyData keyData) throws SVNException {
      final TransparentlyFailedValue<CopyData, SVNException> consumer = new TransparentlyFailedValue<CopyData, SVNException>();
      new FirstInBranch(myVcs, keyData.getRepoUrl(), keyData.getTargetUrl(), keyData.getSourceUrl(), consumer).run();

      final CopyData copyData = consumer.get();
      if (copyData != null) {
        final boolean correct = copyData.isTrunkSupposedCorrect();
        final BranchCopyData branchCopyData;
        if (correct) {
          branchCopyData = new BranchCopyData(keyData.getSourceUrl(), copyData.getCopySourceRevision(), keyData.getTargetUrl(),
                                              copyData.getCopyTargetRevision());
        } else {
          branchCopyData = new BranchCopyData(keyData.getTargetUrl(), copyData.getCopySourceRevision(), keyData.getSourceUrl(),
                                              copyData.getCopyTargetRevision());
        }
        WrapperInvertor<BranchCopyData> invertor = new WrapperInvertor<BranchCopyData>(! correct, branchCopyData);
        if (LOG.isDebugEnabled()) {
          LOG.debug("Loader17 returned: for key: " + keyData.toString() + " result: " + (invertor.toString()));
        }
        return invertor;
      }
      if (LOG.isDebugEnabled()) {
        LOG.debug("Loader17 returned: for key: " + keyData.toString() + " result: null");
      }
      return null;
    }
  }

  private static class KeyData {
    private final String myRepoUrl;
    private final String mySourceUrl;
    private final String myTargetUrl;

    public KeyData(final String repoUID, final String sourceUrl, final String targetUrl) {
      myRepoUrl = repoUID;
      mySourceUrl = sourceUrl;
      myTargetUrl = targetUrl;
    }

    public String getRepoUrl() {
      return myRepoUrl;
    }

    public String getSourceUrl() {
      return mySourceUrl;
    }

    public String getTargetUrl() {
      return myTargetUrl;
    }

    @Override
    public String toString() {
      return "repoURL: " + myRepoUrl + " sourceUrl:" + mySourceUrl + " targetUrl: " + myTargetUrl;
    }
  }

  public static class BranchCopyData implements Invertor<BranchCopyData> {
    private final String mySource;
    private final String myTarget;
    private final long mySourceRevision;
    private final long myTargetRevision;

    public BranchCopyData(String source, long sourceRevision, String target, long targetRevision) {
      mySource = source;
      mySourceRevision = sourceRevision;
      myTarget = target;
      myTargetRevision = targetRevision;
    }

    @Override
    public String toString() {
      return "source: " + mySource + "@" + mySourceRevision + " target: " + myTarget + "@" + myTargetRevision;
    }

    public String getSource() {
      return mySource;
    }

    public long getSourceRevision() {
      return mySourceRevision;
    }

    public String getTarget() {
      return myTarget;
    }

    public long getTargetRevision() {
      return myTargetRevision;
    }

    public BranchCopyData invertSelf() {
      return new BranchCopyData(myTarget, myTargetRevision, mySource, mySourceRevision);
    }
  }

  private interface Invertor<T> {
    T invertSelf();
  }

  public TaskDescriptor getFirstCopyPointTask(final String repoUID, final String sourceUrl, final String targetUrl,
                                          final Consumer<TransparentlyFailedValueI<WrapperInvertor<BranchCopyData>, SVNException>> consumer) {
    return myCalculator.getTask(new KeyData(repoUID, sourceUrl, targetUrl), consumer, SVNException.class);
  }
}


text:
package ro.pub.cs.aipi.lab07.entities;

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

@Entity
@Table(name = "bookstore.language")
public class Language extends PersistentEntity {
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column(name = "id")
	protected Long id;
	@Column(name = "name")
	protected String name;
	@Column(name = "code")
	protected String code;
	@Column(name = "description")
	protected String description;

	public Language() {
	}

	public Language(String name, String code, String description) {
		this.name = name;
		this.code = code;
		this.description = description;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	@Override
	public boolean equals(Object object) {
		if (object == null) {
			return false;
		}
		if (!this.getClass().equals(object.getClass())) {
			return false;
		}
		Language language = (Language) object;
		if ((this.id.equals(language.getId()))
				&& (this.name.equals(language.getName()) && (this.code.equals(language.getCode())))
				&& (this.description.equals(language.getDescription()))) {
			return true;
		}
		return false;
	}
}