text:
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate exonum;
extern crate router;
extern crate bodyparser;
extern crate iron;

use std::path::Path;
use std::fs::File;
use std::io::prelude::*;

use std::collections::HashMap;

use exonum::blockchain::{self, Blockchain, Service, GenesisConfig, ConsensusConfig, ValidatorKeys,
                         Transaction, ApiContext};
use exonum::node::{Node, NodeConfig, NodeApiConfig, TransactionSend, ApiSender, NodeChannel};
use exonum::messages::{RawTransaction, FromRaw, Message};
use exonum::storage::{Fork, MapIndex, LevelDB, LevelDBOptions};
use exonum::crypto::{PublicKey, SecretKey, Hash, HexValue};
use exonum::encoding::{self, Field};
use exonum::api::{Api, ApiError};
use iron::prelude::*;
use iron::Handler;
use router::Router;

// // // // // // // // // // CONSTANTS // // // // // // // // // //
const STORAGE_PATH: &'static str = "~/.db";
// Define service ID for the service trait.

const SERVICE_ID: u16 = 1;

// Define constants for transaction types within the service.

const TX_CREATE_WALLET_ID: u16 = 1;

const TX_TRANSFER_ID: u16 = 2;

// Define initial balance of a newly created wallet.

const INIT_BALANCE: u64 = 100;

// // // // // // // // // // PERSISTENT DATA // // // // // // // // // //

// Declare the data to be stored in the blockchain. In the present case,
// declare a type for storing information about the wallet and its balance.

/// Declare a [serializable][1]
/// [1]: https://github.com/exonum/exonum-doc/blob/master/src/architecture/serialization.md
/// struct and determine bounds of its fields with `encoding_struct!` macro.
encoding_struct! {
    struct Wallet {
        const SIZE = 48;

        field pub_key:            &PublicKey  [00 => 32]
        field name:               &str        [32 => 40]
        field balance:            u64         [40 => 48]
    }
}

/// Add methods to the `Wallet` type for changing balance.
impl Wallet {
    pub fn increase(self, amount: u64) -> Self {
        let balance = self.balance() + amount;
        Self::new(self.pub_key(), self.name(), balance)
    }

    pub fn decrease(self, amount: u64) -> Self {
        let balance = self.balance() - amount;
        Self::new(self.pub_key(), self.name(), balance)
    }
}

// // // // // // // // // // DATA LAYOUT // // // // // // // // // //

/// Create schema of the key-value storage implemented by `MemoryDB`. In the
/// present case a `Fork` of the database is used.
pub struct CurrencySchema<'a> {
    view: &'a mut Fork,
}

/// Declare layout of the data. Use an instance of [`MapIndex`][2]
/// [2]: https://github.com/exonum/exonum-doc/blob/master/src/architecture/storage.md#mapindex
/// to keep wallets in storage. Index values are serialized `Wallet` structs.
///
/// Isolate the wallets map into a separate entity by adding a unique prefix,
/// i.e. the first argument to the `MapIndex::new` call.
impl<'a> CurrencySchema<'a> {
    pub fn wallets(&mut self) -> MapIndex<&mut Fork, PublicKey, Wallet> {
        let prefix = blockchain::gen_prefix(SERVICE_ID, 0, &());
        MapIndex::new(prefix, self.view)
    }

    /// Get a separate wallet from the storage.
    pub fn wallet(&mut self, pub_key: &PublicKey) -> Option<Wallet> {
        self.wallets().get(pub_key)
    }
}

// // // // // // // // // // TRANSACTIONS // // // // // // // // // //

/// Create a new wallet.
message! {
    struct TxCreateWallet {
        const TYPE = SERVICE_ID;
        const ID = TX_CREATE_WALLET_ID;
        const SIZE = 40;

        field pub_key:     &PublicKey  [00 => 32]
        field name:        &str        [32 => 40]
    }
}

/// Transfer coins between the wallets.
message! {
    struct TxTransfer {
        const TYPE = SERVICE_ID;
        const ID = TX_TRANSFER_ID;
        const SIZE = 80;

        field from:        &PublicKey  [00 => 32]
        field to:          &PublicKey  [32 => 64]
        field amount:      u64         [64 => 72]
        field seed:        u64         [72 => 80]
    }
}

// // // // // // // // // // CONTRACTS // // // // // // // // // //

/// Execute a transaction.
impl Transaction for TxCreateWallet {
    /// Verify integrity of the transaction by checking the transaction
    /// signature.
    fn verify(&self) -> bool {
        self.verify_signature(self.pub_key())
    }

    /// Apply logic to the storage when executing the transaction.
    fn execute(&self, view: &mut Fork) {
        let mut schema = CurrencySchema { view };
        if schema.wallet(self.pub_key()).is_none() {
            let wallet = Wallet::new(self.pub_key(), self.name(), INIT_BALANCE);
            println!("Create the wallet: {:?}", wallet);
            schema.wallets().put(self.pub_key(), wallet)
        }
    }
}

impl Transaction for TxTransfer {
    /// Check if the sender is not the receiver. Check correctness of the
    /// sender's signature.
    fn verify(&self) -> bool {
        (*self.from() != *self.to()) && self.verify_signature(self.from())
    }

    /// Retrieve two wallets to apply the transfer. Check the sender's
    /// balance and apply changes to the balances of the wallets.
    fn execute(&self, view: &mut Fork) {
        let mut schema = CurrencySchema { view };
        let sender = schema.wallet(self.from());
        let receiver = schema.wallet(self.to());
        if let (Some(sender), Some(receiver)) = (sender, receiver) {
            let amount = self.amount();
            if sender.balance() >= amount {
                let sender = sender.decrease(amount);
                let receiver = receiver.increase(amount);
                println!("Transfer between wallets: {:?} => {:?}", sender, receiver);
                let mut wallets = schema.wallets();
                wallets.put(self.from(), sender);
                wallets.put(self.to(), receiver);
            }
        }
    }
}

// // // // // // // // // // REST API // // // // // // // // // //

/// Implement the node API.
#[derive(Clone)]
struct CryptocurrencyApi {
    channel: ApiSender<NodeChannel>,
    blockchain: Blockchain,
}

/// Shortcut to get data on wallets.
impl CryptocurrencyApi {
    fn get_wallet(&self, pub_key: &PublicKey) -> Option<Wallet> {
        let mut view = self.blockchain.fork();
        let mut schema = CurrencySchema { view: &mut view };
        schema.wallet(pub_key)
    }

    fn get_wallets(&self) -> Option<Vec<Wallet>> {
        let mut view = self.blockchain.fork();
        let mut schema = CurrencySchema { view: &mut view };
        let idx = schema.wallets();
        let wallets: Vec<Wallet> = idx.values().collect();
        if wallets.is_empty() {
            None
        } else {
            Some(wallets)
        }
    }
}

/// Add an enum which joins transactions of both types to simplify request
/// processing.
#[serde(untagged)]
#[derive(Clone, Serialize, Deserialize)]
enum TransactionRequest {
    CreateWallet(TxCreateWallet),
    Transfer(TxTransfer),
}

/// Implement a trait for the enum for deserialized `TransactionRequest`s
/// to fit into the node channel.
impl Into<Box<Transaction>> for TransactionRequest {
    fn into(self) -> Box<Transaction> {
        match self {
            TransactionRequest::CreateWallet(trans) => Box::new(trans),
            TransactionRequest::Transfer(trans) => Box::new(trans),
        }
    }
}

/// The structure returned by the REST API.
#[derive(Serialize, Deserialize)]
struct TransactionResponse {
    tx_hash: Hash,
}

/// Implement the `Api` trait.
/// `Api` facilitates conversion between transactions/read requests and REST
/// endpoints; for example, it parses `POSTed` JSON into the binary transaction
/// representation used in Exonum internally.
impl Api for CryptocurrencyApi {
    fn wire(&self, router: &mut Router) {
        let self_ = self.clone();
        let transaction = move |req: &mut Request| -> IronResult<Response> {
            match req.get::<bodyparser::Struct<TransactionRequest>>() {
                Ok(Some(transaction)) => {
                    let transaction: Box<Transaction> = transaction.into();
                    let tx_hash = transaction.hash();
                    self_.channel.send(transaction).map_err(ApiError::Events)?;
                    let json = TransactionResponse { tx_hash };
                    self_.ok_response(&serde_json::to_value(&json).unwrap())
                }
                Ok(None) => Err(ApiError::IncorrectRequest("Empty request body".into()))?,
                Err(e) => Err(ApiError::IncorrectRequest(Box::new(e)))?,
            }
        };

        // Gets status of all wallets.
        let self_ = self.clone();
        let wallets_info = move |_: &mut Request| -> IronResult<Response> {
            if let Some(wallets) = self_.get_wallets() {
                self_.ok_response(&serde_json::to_value(wallets).unwrap())
            } else {
                self_.not_found_response(
                    &serde_json::to_value("Wallets database is empty")
                        .unwrap(),
                )
            }
        };

        // Gets status of the wallet corresponding to the public key.
        let self_ = self.clone();
        let wallet_info = move |req: &mut Request| -> IronResult<Response> {
            let path = req.url.path();
            let wallet_key = path.last().unwrap();
            let public_key = PublicKey::from_hex(wallet_key).map_err(ApiError::FromHex)?;
            if let Some(wallet) = self_.get_wallet(&public_key) {
                self_.ok_response(&serde_json::to_value(wallet).unwrap())
            } else {
                self_.not_found_response(&serde_json::to_value("Wallet not found").unwrap())
            }
        };

        // Bind the transaction handler to a specific route.
        router.post("/v1/wallets/transaction", transaction, "transaction");
        router.get("/v1/wallets", wallets_info, "wallets_info");
        router.get("/v1/wallet/:pub_key", wallet_info, "wallet_info");
    }
}

// // // // // // // // // // SERVICE DECLARATION // // // // // // // // // //

/// Define the service.
struct CurrencyService;

/// Implement a `Service` trait for the service.
impl Service for CurrencyService {
    fn service_name(&self) -> &'static str {
        "cryptocurrency"
    }

    fn service_id(&self) -> u16 {
        SERVICE_ID
    }

    /// Implement a method to deserialize transactions coming to the node.
    fn tx_from_raw(&self, raw: RawTransaction) -> Result<Box<Transaction>, encoding::Error> {
        let trans: Box<Transaction> = match raw.message_type() {
            TX_TRANSFER_ID => Box::new(TxTransfer::from_raw(raw)?),
            TX_CREATE_WALLET_ID => Box::new(TxCreateWallet::from_raw(raw)?),
            _ => {
                return Err(encoding::Error::IncorrectMessageType {
                    message_type: raw.message_type(),
                });
            }
        };
        Ok(trans)
    }

    /// Create a REST `Handler` to process web requests to the node.
    fn public_api_handler(&self, ctx: &ApiContext) -> Option<Box<Handler>> {
        let mut router = Router::new();
        let api = CryptocurrencyApi {
            channel: ctx.node_channel().clone(),
            blockchain: ctx.blockchain().clone(),
        };
        api.wire(&mut router);
        Some(Box::new(router))
    }
}

// // // // // // // // // // ENTRY POINT // // // // // // // // // //

fn main() {
    exonum::helpers::init_logger().unwrap();

    println!("Creating in-memory database...");

    let database_options = LevelDBOptions {
        create_if_missing: true,
        error_if_exists: false,
        ..Default::default()
    };
    let db = LevelDB::open(format!("{}/db", STORAGE_PATH), database_options).unwrap();

    //let db = MemoryDB::new();
    let services: Vec<Box<Service>> = vec![Box::new(CurrencyService)];
    let blockchain = Blockchain::new(Box::new(db), services);

    //---------------------------------------

    fn get_file_contents(path: &Path) -> String {
        let mut f = File::open(path).unwrap();
        let mut c = String::new();
        f.read_to_string(&mut c).unwrap();
        c
    }

    let node_keys_buf = get_file_contents(Path::new("keys.keys"));
    let node_keys_strs: Vec<&str> = node_keys_buf.lines().collect();

    let consensus_public_key = PublicKey::from_hex(&node_keys_strs[0]).unwrap();
    let consensus_secret_key = SecretKey::from_hex(&node_keys_strs[1]).unwrap();

    let service_public_key = PublicKey::from_hex(&node_keys_strs[2]).unwrap();
    let service_secret_key = SecretKey::from_hex(&node_keys_strs[3]).unwrap();

    let validator_keys_buf = get_file_contents(Path::new("validator_pub_keys.keys"));
    let validator_keys_strs: Vec<&str> = validator_keys_buf.lines().collect();

    let mut i = 0;
    let mut validator_keys: Vec<ValidatorKeys> = Vec::new();
    while i <= 0 {
        ////////////
        let cons = PublicKey::from_hex(&validator_keys_strs[i]).unwrap();
        let serv = PublicKey::from_hex(&validator_keys_strs[i + 1]).unwrap();
        validator_keys.push(ValidatorKeys {
            consensus_key: cons,
            service_key: serv,
        });
        i += 2;
    }

    // let key: PublicKey = PublicKey::from_hex("16ef83ca4b231404daec6d07b24beb84d89c25944285d2e32a2dcf8f0f3eda72").unwrap();

    //let consensus_public_key = PublicKey::from_hex("16ef83ca4b231404daec6d07b24beb84d89c25944285d2e32a2dcf8f0f3eda72").unwrap();
    //let consensus_secret_key = SecretKey::from_hex("2a751e6595af66f7644bd33cf7710b6226cf8d0de4b3d18bc8fc2d80f19325a716ef83ca4b231404daec6d07b24beb84d89c25944285d2e32a2dcf8f0f3eda72").unwrap();

    //let service_public_key = PublicKey::from_hex("523ead8ea8457de570e165a512dd5d1b6688cb5757c3d744e03d1173f3e3e237").unwrap();
    //let service_secret_key = SecretKey::from_hex("18544ebbf3ceeeebca847fe6b4e6ce88f83fc92b6b0e24d5466f3cd08aea37bb523ead8ea8457de570e165a512dd5d1b6688cb5757c3d744e03d1173f3e3e237").unwrap();

    //let (consensus_public_key, consensus_secret_key) = (PublicKey::from_hex("16ef83ca4b231404daec6d07b24beb84d89c25944285d2e32a2dcf8f0f3eda72").unwrap(), SecretKey::from_hex("2a751e6595af66f7644bd33cf7710b6226cf8d0de4b3d18bc8fc2d80f19325a716ef83ca4b231404daec6d07b24beb84d89c25944285d2e32a2dcf8f0f3eda72"));
    //let (service_public_key, service_secret_key) = PublicKey::from_hex("16ef83ca4b231404daec6d07b24beb84d89c25944285d2e32a2dcf8f0f3eda72").unwrap();

    //println!("{}",key);

//    let validator_keys = ValidatorKeys {
//        consensus_key: consensus_public_key,
//        service_key: service_public_key,
//    };

    let consensus_config = ConsensusConfig {
        txs_block_limit: 1,
        ..Default::default()
    };

    let genesis = GenesisConfig::new_with_consensus(consensus_config, validator_keys.into_iter());

    let api_address = "0.0.0.0:8000".parse().unwrap();
    let api_cfg = NodeApiConfig {
        public_api_address: Some(api_address),
        enable_blockchain_explorer: true,
        state_update_timeout: 1_000,
        ..Default::default()
    };

    let peer_address = "0.0.0.0:8001".parse().unwrap();

    let node_cfg = NodeConfig {
        listen_address: peer_address,
        peers: vec![
            //"185.35.221.11:8000".parse().unwrap(),
            "185.35.221.11:8001".parse().unwrap(),
            "54.252.175.39:8001".parse().unwrap()
        ],
        service_public_key,
        service_secret_key,
        consensus_public_key,
        consensus_secret_key,
        genesis,
        external_address: None,
        network: Default::default(),
        whitelist: Default::default(),
        api: api_cfg,
        mempool: Default::default(),
        services_configs: Default::default(),
    };

    println!("Starting a single node...");
    let mut node = Node::new(blockchain, node_cfg);

    println!("Blockchain is ready for transactions!");
    node.run().unwrap();
}


text:
import {InfrastructureObject} from "../infrastructureObject";
import {ParameterTypes} from "./parameterTypes";
import {PropertyFields} from "../logic/propertyFields";

const bluebird = require('bluebird');
const path = require('path');
const fsExtra = require('fs-extra');

/**
 * Debug and internal facades
 */
class DebugFacades extends InfrastructureObject {

    public async demoStep(stepProperties: {async: boolean, failed: boolean, skipped: boolean}) {
        this.log(`Executing demo step with properties = ${JSON.stringify(stepProperties)}`);
        if (stepProperties.async) await bluebird.delay(2000);
        if (stepProperties.failed) throw new Error('This is a failed step');

        // TODO: handle skipped
    }

    public async printVariable(variable) {
        const processed = await this.infra.utils.variableProcessor.processVariables(variable);
        this.log(processed);
    }

    public async evalCode(userCode: string) {
        if (this.infra.config.utils.debug.warnOnCodeEval) this.log('ERROR: DEBUG STEP - SHOULD NEVER BE USED IN PRODUCTION');

        const $ = this.infra;
        return bluebird.try(() => {
            // tslint:disable-next-line:prefer-const
            let userCodeResult;
            // tslint:disable-next-line:no-eval
            let result = eval(userCode);
            if (userCodeResult !== undefined) result = userCodeResult;
            return result;
        }).catch(e => {
            throw new Error('Error running user code ' + e.toString());
        });
    }

}

export {DebugFacades};

redpajama_set_name: RedPajamaGithub


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package erp.mod.hrs.db;

import erp.mod.SModConsts;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import sa.gui.util.SUtilConsts;
import sa.lib.SLibConsts;
import sa.lib.SLibUtils;
import sa.lib.db.SDbConsts;
import sa.lib.db.SDbRegistryUser;
import sa.lib.gui.SGuiSession;

/**
 *
 * @author Néstor Ávalos, Edwin Carmona, Sergio Flores
 */
public class SDbConfig extends SDbRegistryUser {

    protected int mnPkConfigId;
    protected Date mtDateOperations;
    protected int mnFirstDayWeek;
    protected int mnLimitMwzReference;
    protected String msNumberSeries;
    protected String msSsSubbranch;
    protected String msBajioAffinityGroup;
    protected double mdPayrollTaxRate;
    protected int mnPrePayrollWeeklyCutoffDayWeek;  // Pre payroll weekly (regular income) cutoff day: 1=Su, 2=Mo, 3=Tu, ... Sa=7
    protected int mnPrePayrollWeeklyWeeksLag;       // Pre payroll weekly (regular income) weeks lag: 0 = current week; 1 = one week behind; and so forth.
    protected int mnPrePayrollWeeklyVariableCutoffDayWeek;  // Pre payroll weekly (variable income) cutoff day: 1=Su, 2=Mo, 3=Tu, ... Sa=7
    protected int mnPrePayrollWeeklyVariableWeeksLag;       // Pre payroll weekly (variable income) weeks lag: 0 = current week; 1 = one week behind; and so forth.
    protected int mnTimeClockPolicy;
    protected boolean mbFortnightStandard;
    protected boolean mbAutoVacationBonus;
    protected boolean mbTaxSubsidyEarning;
    protected boolean mbTaxNet;
    protected boolean mbBankAccountUse;
    //protected boolean mbDeleted;
    protected int mnFkMwzTypeId;
    protected int mnFkMwzReferenceTypeId;
    protected int mnFkTaxComputationTypeId;
    protected int mnFkBankId;
    protected int mnFkEarningEarningId_n;
    protected int mnFkEarningVacationId_n;
    protected int mnFkEarningTaxId_n;
    protected int mnFkEarningTaxSubsidyId_n;
    protected int mnFkEarningTaxSubsidyCompensatedId_n;
    protected int mnFkEarningSsContributionId_n;
    protected int mnFkEarningOvertime_2_Id_n;
    protected int mnFkEarningOvertime_3_Id_n;
    protected int mnFkEarningHolidayId_n;
    protected int mnFkEarningDayOffId_n;
    protected int mnFkEarningSunBonusId_n;
    protected int mnFkDeductionTaxId_n;
    protected int mnFkDeductionTaxSubsidyId_n;
    protected int mnFkDeductionSsContributionId_n;
    /*
    protected int mnFkUserInsertId;
    protected int mnFkUserUpdateId;
    protected Date mtTsUserInsert;
    protected Date mtTsUserUpdate;
    */

    public SDbConfig() {
        super(SModConsts.HRS_CFG);
    }

    public void setPkConfigId(int n) { mnPkConfigId = n; }
    public void setDateOperations(Date t) { mtDateOperations = t; }
    public void setFirstDayWeek(int n) { mnFirstDayWeek = n; }
    public void setLimitMwzReference(int n) { mnLimitMwzReference = n; }
    public void setNumberSeries(String s) { msNumberSeries = s; }
    public void setSsSubbranch(String s) { msSsSubbranch = s; }
    public void setBajioAffinityGroup(String s) { msBajioAffinityGroup = s; }
    public void setPayrollTaxRate(double d) { mdPayrollTaxRate = d; }
    public void setPrePayrollWeeklyCutoffDayWeek(int n) { mnPrePayrollWeeklyCutoffDayWeek = n; }
    public void setPrePayrollWeeklyWeeksLag(int n) { mnPrePayrollWeeklyWeeksLag = n; }
    public void setPrePayrollWeeklyVarCutoffDayWeek(int n) { mnPrePayrollWeeklyVariableCutoffDayWeek = n; }
    public void setPrePayrollWeeklyVarWeeksLag(int n) { mnPrePayrollWeeklyVariableWeeksLag = n; }
    public void setTimeClockPolicy(int n) { mnTimeClockPolicy = n; }
    public void setFortnightStandard(boolean b) { mbFortnightStandard = b; }
    public void setAutoVacationBonus(boolean b) { mbAutoVacationBonus = b; }
    public void setTaxSubsidyEarning(boolean b) { mbTaxSubsidyEarning = b; }
    public void setTaxNet(boolean b) { mbTaxNet = b; }
    public void setBankAccountUse(boolean b) { mbBankAccountUse = b; }
    public void setDeleted(boolean b) { mbDeleted = b; }
    public void setFkMwzTypeId(int n) { mnFkMwzTypeId = n; }
    public void setFkMwzReferenceTypeId(int n) { mnFkMwzReferenceTypeId = n; }
    public void setFkTaxComputationTypeId(int n) { mnFkTaxComputationTypeId = n; }
    public void setFkBankId(int n) { mnFkBankId = n; }
    public void setFkEarningEarningId_n(int n) { mnFkEarningEarningId_n = n; }
    public void setFkEarningVacationId_n(int n) { mnFkEarningVacationId_n = n; }
    public void setFkEarningTaxId_n(int n) { mnFkEarningTaxId_n = n; }
    public void setFkEarningTaxSubsidyId_n(int n) { mnFkEarningTaxSubsidyId_n = n; }
    public void setFkEarningTaxSubsidyCompensatedId_n(int n) { mnFkEarningTaxSubsidyCompensatedId_n = n; }
    public void setFkEarningSsContributionId_n(int n) { mnFkEarningSsContributionId_n = n; }
    public void setFkEarningOvertime2Id_n(int n) { mnFkEarningOvertime_2_Id_n = n; }
    public void setFkEarningOvertime3Id_n(int n) { mnFkEarningOvertime_3_Id_n = n; }
    public void setFkEarningHolidayId_n(int n) { mnFkEarningHolidayId_n = n; }
    public void setFkEarningDayOffId_n(int n) { mnFkEarningDayOffId_n = n; }
    public void setFkEarningSunBonusId_n(int n) { mnFkEarningSunBonusId_n = n; }
    public void setFkDeductionTaxId_n(int n) { mnFkDeductionTaxId_n = n; }
    public void setFkDeductionTaxSubsidyId_n(int n) { mnFkDeductionTaxSubsidyId_n = n; }
    public void setFkDeductionSsContributionId_n(int n) { mnFkDeductionSsContributionId_n = n; }
    public void setFkUserInsertId(int n) { mnFkUserInsertId = n; }
    public void setFkUserUpdateId(int n) { mnFkUserUpdateId = n; }
    public void setTsUserInsert(Date t) { mtTsUserInsert = t; }
    public void setTsUserUpdate(Date t) { mtTsUserUpdate = t; }

    public int getPkConfigId() { return mnPkConfigId; }
    public Date getDateOperations() { return mtDateOperations; }
    public int getFirstDayWeek() { return mnFirstDayWeek; }
    public int getLimitMwzReference() { return mnLimitMwzReference; }
    public String getNumberSeries() { return msNumberSeries; }
    public String getSsSubbranch() { return msSsSubbranch; }
    public String getBajioAffinityGroup() { return msBajioAffinityGroup; }
    public double getPayrollTaxRate() { return mdPayrollTaxRate; }
    /**
     * Pre payroll weekly cutoff day: 1=Su, 2=Mo, 3=Tu, ... Sa=7
     */
    public int getPrePayrollWeeklyCutoffDayWeek() { return mnPrePayrollWeeklyCutoffDayWeek; }
    public int getPrePayrollWeeklyWeeksLag() { return mnPrePayrollWeeklyWeeksLag; }
    public int PrePayrollWeeklyVarCutoffDayWeek() { return mnPrePayrollWeeklyVariableCutoffDayWeek; }
    public int PrePayrollWeeklyVarWeeksLag() { return mnPrePayrollWeeklyVariableWeeksLag; }
    public int getTimeClockPolicy() { return mnTimeClockPolicy; }
    public boolean isFortnightStandard() { return mbFortnightStandard; }
    public boolean isAutoVacationBonus() { return mbAutoVacationBonus; }
    public boolean isTaxSubsidyEarning() { return mbTaxSubsidyEarning; }
    public boolean isTaxNet() { return mbTaxNet; }
    public boolean isBankAccountUse() { return mbBankAccountUse; }
    public boolean isDeleted() { return mbDeleted; }
    public int getFkMwzTypeId() { return mnFkMwzTypeId; }
    public int getFkMwzReferenceTypeId() { return mnFkMwzReferenceTypeId; }
    public int getFkTaxComputationTypeId() { return mnFkTaxComputationTypeId; }
    public int getFkBankId() { return mnFkBankId; }
    public int getFkEarningEarningId_n() { return mnFkEarningEarningId_n; }
    public int getFkEarningVacationId_n() { return mnFkEarningVacationId_n; }
    public int getFkEarningTaxId_n() { return mnFkEarningTaxId_n; }
    public int getFkEarningTaxSubsidyId_n() { return mnFkEarningTaxSubsidyId_n; }
    public int getFkEarningTaxSubsidyCompensatedId_n() { return mnFkEarningTaxSubsidyCompensatedId_n; }
    public int getFkEarningSsContributionId_n() { return mnFkEarningSsContributionId_n; }
    public int getFkEarningOvertime2Id_n() { return mnFkEarningOvertime_2_Id_n; }
    public int getFkEarningOvertime3Id_n() { return mnFkEarningOvertime_3_Id_n; }
    public int getFkEarningHolidayId_n() { return mnFkEarningHolidayId_n; }
    public int getFkEarningDayOffId_n() { return mnFkEarningDayOffId_n; }
    public int getFkEarningSunBonusId_n() { return mnFkEarningSunBonusId_n; }
    public int getFkDeductionTaxId_n() { return mnFkDeductionTaxId_n; }
    public int getFkDeductionTaxSubsidyId_n() { return mnFkDeductionTaxSubsidyId_n; }
    public int getFkDeductionSsContributionId_n() { return mnFkDeductionSsContributionId_n; }
    public int getFkUserInsertId() { return mnFkUserInsertId; }
    public int getFkUserUpdateId() { return mnFkUserUpdateId; }
    public Date getTsUserInsert() { return mtTsUserInsert; }
    public Date getTsUserUpdate() { return mtTsUserUpdate; }

    @Override
    public void setPrimaryKey(int[] pk) {
        mnPkConfigId = pk[0];
    }

    @Override
    public int[] getPrimaryKey() {
        return new int[] { mnPkConfigId };
    }

    @Override
    public void initRegistry() {
        initBaseRegistry();

        mnPkConfigId = 0;
        mtDateOperations = null;
        mnFirstDayWeek = 0;
        mnLimitMwzReference = 0;
        msNumberSeries = "";
        msSsSubbranch = "";
        msBajioAffinityGroup = "";
        mdPayrollTaxRate = 0;
        mnPrePayrollWeeklyCutoffDayWeek = 0;
        mnPrePayrollWeeklyWeeksLag = 0;
        mnPrePayrollWeeklyVariableCutoffDayWeek = 0;
        mnPrePayrollWeeklyVariableWeeksLag = 0;
        mnTimeClockPolicy = 0;
        mbFortnightStandard = false;
        mbAutoVacationBonus = false;
        mbTaxSubsidyEarning = false;
        mbTaxNet = false;
        mbBankAccountUse = false;
        mbDeleted = false;
        mnFkMwzTypeId = 0;
        mnFkMwzReferenceTypeId = 0;
        mnFkTaxComputationTypeId = 0;
        mnFkBankId = 0;
        mnFkEarningEarningId_n = 0;
        mnFkEarningVacationId_n = 0;
        mnFkEarningTaxId_n = 0;
        mnFkEarningTaxSubsidyId_n = 0;
        mnFkEarningTaxSubsidyCompensatedId_n = 0;
        mnFkEarningSsContributionId_n = 0;
        mnFkEarningOvertime_2_Id_n = 0;
        mnFkEarningOvertime_3_Id_n = 0;
        mnFkEarningHolidayId_n = 0;
        mnFkEarningDayOffId_n = 0;
        mnFkEarningSunBonusId_n = 0;
        mnFkDeductionTaxId_n = 0;
        mnFkDeductionTaxSubsidyId_n = 0;
        mnFkDeductionSsContributionId_n = 0;
        mnFkUserInsertId = 0;
        mnFkUserUpdateId = 0;
        mtTsUserInsert = null;
        mtTsUserUpdate = null;
    }

    @Override
    public String getSqlTable() {
        return SModConsts.TablesMap.get(mnRegistryType);
    }

    @Override
    public String getSqlWhere() {
        return "WHERE id_cfg = " + mnPkConfigId + " ";
    }

    @Override
    public String getSqlWhere(int[] pk) {
        return "WHERE id_cfg = " + pk[0] + " ";
    }

    @Override
    public void computePrimaryKey(SGuiSession session) throws SQLException, Exception {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void read(SGuiSession session, int[] pk) throws SQLException, Exception {
        ResultSet resultSet = null;

        initRegistry();
        initQueryMembers();
        mnQueryResultId = SDbConsts.READ_ERROR;

        msSql = "SELECT * " + getSqlFromWhere(pk);
        resultSet = session.getStatement().executeQuery(msSql);
        if (!resultSet.next()) {
            throw new Exception(SDbConsts.ERR_MSG_REG_NOT_FOUND);
        }
        else {
            mnPkConfigId = resultSet.getInt("id_cfg");
            mtDateOperations = resultSet.getDate("dt_ops");
            mnFirstDayWeek = resultSet.getInt("fst_day_wee");
            mnLimitMwzReference = resultSet.getInt("lim_mwz_ref");
            msNumberSeries = resultSet.getString("num_ser");
            msSsSubbranch = resultSet.getString("ss_subbra");
            msBajioAffinityGroup = resultSet.getString("baj_aff_grp");
            mdPayrollTaxRate = resultSet.getDouble("pay_tax_rate");
            mnPrePayrollWeeklyCutoffDayWeek = resultSet.getInt("pre_pay_wee_cut_day_wee");
            mnPrePayrollWeeklyWeeksLag = resultSet.getInt("pre_pay_wee_wee_lag");
            mnPrePayrollWeeklyVariableCutoffDayWeek = resultSet.getInt("pre_pay_wee_var_cut_day_wee");
            mnPrePayrollWeeklyVariableWeeksLag = resultSet.getInt("pre_pay_wee_var_wee_lag");
            mnTimeClockPolicy = resultSet.getInt("time_clock_pol");
            mbFortnightStandard = resultSet.getBoolean("b_for_std");
            mbAutoVacationBonus = resultSet.getBoolean("b_auto_vac_bon");
            mbTaxSubsidyEarning = resultSet.getBoolean("b_tax_sub_ear");
            mbTaxNet = resultSet.getBoolean("b_tax_net");
            mbBankAccountUse = resultSet.getBoolean("b_bank_acc_use");
            mbDeleted = resultSet.getBoolean("b_del");
            mnFkMwzTypeId = resultSet.getInt("fk_tp_mwz");
            mnFkMwzReferenceTypeId = resultSet.getInt("fk_tp_mwz_ref");
            mnFkTaxComputationTypeId = resultSet.getInt("fk_tp_tax_comp");
            mnFkBankId = resultSet.getInt("fk_bank");
            mnFkEarningEarningId_n = resultSet.getInt("fk_ear_ear_n");
            mnFkEarningVacationId_n = resultSet.getInt("fk_ear_vac_n");
            mnFkEarningTaxId_n = resultSet.getInt("fk_ear_tax_n");
            mnFkEarningTaxSubsidyId_n = resultSet.getInt("fk_ear_tax_sub_n");
            mnFkEarningTaxSubsidyCompensatedId_n = resultSet.getInt("fk_ear_tax_sub_comp_n");
            mnFkEarningSsContributionId_n = resultSet.getInt("fk_ear_ssc_n");
            mnFkEarningOvertime_2_Id_n = resultSet.getInt("fk_ear_overtime_2_n");
            mnFkEarningOvertime_3_Id_n = resultSet.getInt("fk_ear_overtime_3_n");
            mnFkEarningHolidayId_n = resultSet.getInt("fk_ear_holiday_n");
            mnFkEarningDayOffId_n = resultSet.getInt("fk_ear_day_off_n");
            mnFkEarningSunBonusId_n = resultSet.getInt("fk_ear_sun_bonus_n");
            mnFkDeductionTaxId_n = resultSet.getInt("fk_ded_tax_n");
            mnFkDeductionTaxSubsidyId_n = resultSet.getInt("fk_ded_tax_sub_n");
            mnFkDeductionSsContributionId_n = resultSet.getInt("fk_ded_ssc_n");
            mnFkUserInsertId = resultSet.getInt("fk_usr_ins");
            mnFkUserUpdateId = resultSet.getInt("fk_usr_upd");
            mtTsUserInsert = resultSet.getTimestamp("ts_usr_ins");
            mtTsUserUpdate = resultSet.getTimestamp("ts_usr_upd");

            mbRegistryNew = false;
        }

        mnQueryResultId = SDbConsts.READ_OK;
    }

    @Override
    public void save(SGuiSession session) throws SQLException, Exception {
        initQueryMembers();
        mnQueryResultId = SDbConsts.SAVE_ERROR;

        if (mbRegistryNew) {
            verifyRegistryNew(session);
        }

        if (mbRegistryNew) {
            mbDeleted = false;
            mnFkUserInsertId = session.getUser().getPkUserId();
            mnFkUserUpdateId = SUtilConsts.USR_NA_ID;

            msSql = "INSERT INTO " + getSqlTable() + " VALUES (" +
                    mnPkConfigId + ", " +
                    "'" + SLibUtils.DbmsDateFormatDate.format(mtDateOperations) + "', " +
                    mnFirstDayWeek + ", " +
                    mnLimitMwzReference + ", " +
                    "'" + msNumberSeries + "', " +
                    "'" + msSsSubbranch + "', " +
                    "'" + msBajioAffinityGroup + "', " +
                    mdPayrollTaxRate + ", " +
                    mnPrePayrollWeeklyCutoffDayWeek + ", " +
                    mnPrePayrollWeeklyWeeksLag + ", " +
                    mnPrePayrollWeeklyVariableCutoffDayWeek + ", " +
                    mnPrePayrollWeeklyVariableWeeksLag + ", " +
                    mnTimeClockPolicy + ", " +
                    (mbFortnightStandard ? 1 : 0) + ", " +
                    (mbAutoVacationBonus ? 1 : 0) + ", " +
                    (mbTaxSubsidyEarning ? 1 : 0) + ", " +
                    (mbTaxNet ? 1 : 0) + ", " +
                    (mbBankAccountUse ? 1 : 0) + ", " +
                    (mbDeleted ? 1 : 0) + ", " +
                    mnFkMwzTypeId + ", " +
                    mnFkMwzReferenceTypeId + ", " +
                    mnFkTaxComputationTypeId + ", " +
                    mnFkBankId + ", " +
                    (mnFkEarningEarningId_n == SLibConsts.UNDEFINED ? "NULL" : "" + mnFkEarningEarningId_n) + ", " +
                    (mnFkEarningVacationId_n  == SLibConsts.UNDEFINED ? "NULL" : "" + mnFkEarningVacationId_n) + ", " +
                    (mnFkEarningTaxId_n == SLibConsts.UNDEFINED ? "NULL" : "" + mnFkEarningTaxId_n) + ", " +
                    (mnFkEarningTaxSubsidyId_n == SLibConsts.UNDEFINED ? "NULL" : "" + mnFkEarningTaxSubsidyId_n) + ", " +
                    (mnFkEarningTaxSubsidyCompensatedId_n == SLibConsts.UNDEFINED ? "NULL" : "" + mnFkEarningTaxSubsidyCompensatedId_n) + ", " +
                    (mnFkEarningSsContributionId_n == SLibConsts.UNDEFINED ? "NULL" : "" + mnFkEarningSsContributionId_n) + ", " +
                    (mnFkEarningOvertime_2_Id_n == SLibConsts.UNDEFINED ? "NULL" : "" + mnFkEarningOvertime_2_Id_n) + ", " +
                    (mnFkEarningOvertime_3_Id_n == SLibConsts.UNDEFINED ? "NULL" : "" + mnFkEarningOvertime_3_Id_n) + ", " +
                    (mnFkEarningHolidayId_n == SLibConsts.UNDEFINED ? "NULL" : "" + mnFkEarningHolidayId_n) + ", " +
                    (mnFkEarningDayOffId_n == SLibConsts.UNDEFINED ? "NULL" : "" + mnFkEarningDayOffId_n) + ", " +
                    (mnFkEarningSunBonusId_n == SLibConsts.UNDEFINED ? "NULL" : "" + mnFkEarningSunBonusId_n) + ", " +
                    (mnFkDeductionTaxId_n == SLibConsts.UNDEFINED ? "NULL" : "" + mnFkDeductionTaxId_n) + ", " +
                    (mnFkDeductionTaxSubsidyId_n == SLibConsts.UNDEFINED ? "NULL" : "" + mnFkDeductionTaxSubsidyId_n) + ", " +
                    (mnFkDeductionSsContributionId_n == SLibConsts.UNDEFINED ? "NULL" : "" + mnFkDeductionSsContributionId_n) + ", " +
                    mnFkUserInsertId + ", " +
                    mnFkUserUpdateId + ", " +
                    "NOW()" + ", " +
                    "NOW()" + " " +
                    ")";
        }
        else {
            mnFkUserUpdateId = session.getUser().getPkUserId();

            msSql = "UPDATE " + getSqlTable() + " SET " +
                    //"id_cfg = " + mnPkConfigId + ", " +
                    "dt_ops = '" + SLibUtils.DbmsDateFormatDate.format(mtDateOperations) + "', " +
                    "fst_day_wee = " + mnFirstDayWeek + ", " +
                    "lim_mwz_ref = " + mnLimitMwzReference + ", " +
                    "num_ser = '" + msNumberSeries + "', " +
                    "ss_subbra = '" + msSsSubbranch + "', " +
                    "baj_aff_grp = '" + msBajioAffinityGroup + "', " +
                    "pay_tax_rate = " + mdPayrollTaxRate + ", " +
                    "pre_pay_wee_cut_day_wee = " + mnPrePayrollWeeklyCutoffDayWeek + ", " +
                    "pre_pay_wee_wee_lag = " + mnPrePayrollWeeklyWeeksLag + ", " +
                    "pre_pay_wee_var_cut_day_wee = " + mnPrePayrollWeeklyVariableCutoffDayWeek + ", " +
                    "pre_pay_wee_var_wee_lag = " + mnPrePayrollWeeklyVariableWeeksLag + ", " +
                    "time_clock_pol = " + mnTimeClockPolicy + ", " +
                    "b_for_std = " + (mbFortnightStandard ? 1 : 0) + ", " +
                    "b_auto_vac_bon = " + (mbAutoVacationBonus ? 1 : 0) + ", " +
                    "b_tax_sub_ear = " + (mbTaxSubsidyEarning ? 1 : 0) + ", " +
                    "b_tax_net = " + (mbTaxNet ? 1 : 0) + ", " +
                    "b_bank_acc_use = " + (mbBankAccountUse ? 1 : 0) + ", " +
                    "b_del = " + (mbDeleted ? 1 : 0) + ", " +
                    "fk_tp_mwz = " + mnFkMwzTypeId + ", " +
                    "fk_tp_mwz_ref = " + mnFkMwzReferenceTypeId + ", " +
                    "fk_tp_tax_comp = " + mnFkTaxComputationTypeId + ", " +
                    "fk_bank = " + mnFkBankId + ", " +
                    "fk_ear_ear_n = " + (mnFkEarningEarningId_n == SLibConsts.UNDEFINED ? "NULL" : "" + mnFkEarningEarningId_n) + ", " +
                    "fk_ear_vac_n = " + (mnFkEarningVacationId_n  == SLibConsts.UNDEFINED ? "NULL" : "" + mnFkEarningVacationId_n) + ", " +
                    "fk_ear_tax_n = " + (mnFkEarningTaxId_n == SLibConsts.UNDEFINED ? "NULL" : "" + mnFkEarningTaxId_n) + ", " +
                    "fk_ear_tax_sub_n = " + (mnFkEarningTaxSubsidyId_n == SLibConsts.UNDEFINED ? "NULL" : "" + mnFkEarningTaxSubsidyId_n) + ", " +
                    "fk_ear_tax_sub_comp_n = " + (mnFkEarningTaxSubsidyCompensatedId_n == SLibConsts.UNDEFINED ? "NULL" : "" + mnFkEarningTaxSubsidyCompensatedId_n) + ", " +
                    "fk_ear_ssc_n = " + (mnFkEarningSsContributionId_n == SLibConsts.UNDEFINED ? "NULL" : "" + mnFkEarningSsContributionId_n) + ", " +
                    "fk_ear_overtime_2_n = " + (mnFkEarningOvertime_2_Id_n == SLibConsts.UNDEFINED ? "NULL" : "" + mnFkEarningOvertime_2_Id_n) + ", " +
                    "fk_ear_overtime_3_n = " + (mnFkEarningOvertime_3_Id_n == SLibConsts.UNDEFINED ? "NULL" : "" + mnFkEarningOvertime_3_Id_n) + ", " +
                    "fk_ear_holiday_n = " + (mnFkEarningHolidayId_n == SLibConsts.UNDEFINED ? "NULL" : "" + mnFkEarningHolidayId_n) + ", " +
                    "fk_ear_day_off_n = " + (mnFkEarningDayOffId_n == SLibConsts.UNDEFINED ? "NULL" : "" + mnFkEarningDayOffId_n) + ", " +
                    "fk_ear_sun_bonus_n = " + (mnFkEarningSunBonusId_n == SLibConsts.UNDEFINED ? "NULL" : "" + mnFkEarningSunBonusId_n) + ", " +
                    "fk_ded_tax_n = " + (mnFkDeductionTaxId_n == SLibConsts.UNDEFINED ? "NULL" : "" + mnFkDeductionTaxId_n) + ", " +
                    "fk_ded_tax_sub_n = " + (mnFkDeductionTaxSubsidyId_n == SLibConsts.UNDEFINED ? "NULL" : "" + mnFkDeductionTaxSubsidyId_n) + ", " +
                    "fk_ded_ssc_n = " + (mnFkDeductionSsContributionId_n == SLibConsts.UNDEFINED ? "NULL" : "" + mnFkDeductionSsContributionId_n) + ", " +
                    //"fk_usr_ins = " + mnFkUserInsertId + ", " +
                    "fk_usr_upd = " + mnFkUserUpdateId + ", " +
                    //"ts_usr_ins = " + "NOW()" + ", " +
                    "ts_usr_upd = " + "NOW()" + " " +
                    getSqlWhere();
        }

        session.getStatement().execute(msSql);
        mbRegistryNew = false;
        mnQueryResultId = SDbConsts.SAVE_OK;
    }

    @Override
    public SDbConfig clone() throws CloneNotSupportedException {
        SDbConfig registry = new SDbConfig();

        registry.setPkConfigId(this.getPkConfigId());
        registry.setDateOperations(this.getDateOperations());
        registry.setFirstDayWeek(this.getFirstDayWeek());
        registry.setLimitMwzReference(this.getLimitMwzReference());
        registry.setNumberSeries(this.getNumberSeries());
        registry.setSsSubbranch(this.getSsSubbranch());
        registry.setBajioAffinityGroup(this.getBajioAffinityGroup());
        registry.setPayrollTaxRate(this.getPayrollTaxRate());
        registry.setPrePayrollWeeklyCutoffDayWeek(this.getPrePayrollWeeklyCutoffDayWeek());
        registry.setPrePayrollWeeklyWeeksLag(this.getPrePayrollWeeklyWeeksLag());
        registry.setPrePayrollWeeklyVarCutoffDayWeek(this.PrePayrollWeeklyVarCutoffDayWeek());
        registry.setPrePayrollWeeklyVarWeeksLag(this.PrePayrollWeeklyVarWeeksLag());
        registry.setTimeClockPolicy(this.getTimeClockPolicy());
        registry.setFortnightStandard(this.isFortnightStandard());
        registry.setAutoVacationBonus(this.isAutoVacationBonus());
        registry.setTaxSubsidyEarning(this.isTaxSubsidyEarning());
        registry.setTaxNet(this.isTaxNet());
        registry.setBankAccountUse(this.isBankAccountUse());
        registry.setDeleted(this.isDeleted());
        registry.setFkMwzTypeId(this.getFkMwzTypeId());
        registry.setFkMwzReferenceTypeId(this.getFkMwzReferenceTypeId());
        registry.setFkTaxComputationTypeId(this.getFkTaxComputationTypeId());
        registry.setFkBankId(this.getFkBankId());
        registry.setFkEarningEarningId_n(this.getFkEarningEarningId_n());
        registry.setFkEarningVacationId_n(this.getFkEarningVacationId_n());
        registry.setFkEarningTaxId_n(this.getFkEarningTaxId_n());
        registry.setFkEarningTaxSubsidyId_n(this.getFkEarningTaxSubsidyId_n());
        registry.setFkEarningTaxSubsidyCompensatedId_n(this.getFkEarningTaxSubsidyCompensatedId_n());
        registry.setFkEarningSsContributionId_n(this.getFkEarningSsContributionId_n());
        registry.setFkEarningOvertime2Id_n(this.getFkEarningOvertime2Id_n());
        registry.setFkEarningOvertime3Id_n(this.getFkEarningOvertime3Id_n());
        registry.setFkEarningHolidayId_n(this.getFkEarningHolidayId_n());
        registry.setFkEarningDayOffId_n(this.getFkEarningDayOffId_n());
        registry.setFkEarningSunBonusId_n(this.getFkEarningSunBonusId_n());
        registry.setFkDeductionTaxId_n(this.getFkDeductionTaxId_n());
        registry.setFkDeductionTaxSubsidyId_n(this.getFkDeductionTaxSubsidyId_n());
        registry.setFkDeductionSsContributionId_n(this.getFkDeductionSsContributionId_n());
        registry.setFkUserInsertId(this.getFkUserInsertId());
        registry.setFkUserUpdateId(this.getFkUserUpdateId());
        registry.setTsUserInsert(this.getTsUserInsert());
        registry.setTsUserUpdate(this.getTsUserUpdate());

        registry.setRegistryNew(this.isRegistryNew());
        return registry;
    }
}


text:
package scala.pickling.runtime.spec

import scala.pickling._, Defaults._
import org.scalacheck.{Properties, Prop, Gen}
import Gen._

case class C(x: Int)
case class D(x: Int, y: Double)
case class E(x: Int, y: String)
case class F(x: Int, y: C)
case class G(a: Array[Int])

object RuntimeJsonSpec extends Properties("runtime-json") {
  import json._

  // there's no way to actually use any of our testing frameworks
  // to guarantee that the runtime picklers are being used
  // though by calling pickle on something that's statically
  // resolved to be Any will always trigger runtime pickling
  def roundTrip(obj: Any): Boolean = {
    val p = obj.pickle
    val up = p.unpickle[Any]
    obj == up
  }

  // there's no way to actually use any of our testing frameworks
  // to guarantee that the runtime picklers are being used
  // though by calling pickle on something that's statically
  // resolved to be Any will always trigger runtime pickling
  def roundTripG(obj: Any): Boolean = {
    val p = obj.pickle
    val up = p.unpickle[Any]
    obj.asInstanceOf[G].a.mkString(",") == up.asInstanceOf[G].a.mkString(",")
  }

  property("Int") = Prop forAll { (i: Int) =>
    roundTrip(i)
  }

  property("Double") = Prop forAll { (d: Double) =>
    roundTrip(d)
  }

  property("Long") = Prop forAll { (l: Long) =>
    roundTrip(l)
  }

  property("Char") = Prop forAll { (c: Char) =>
    roundTrip(c)
  }

  property("Float") = Prop forAll { (f: Float) =>
    roundTrip(f)
  }

  property("Boolean") = Prop forAll { (b: Boolean) =>
    roundTrip(b)
  }

  property("Short") = Prop forAll { (s: Short) =>
    roundTrip(s)
  }

  property("Byte") = Prop forAll { (b: Byte) =>
    roundTrip(b)
  }

  // It seems like Unit doesn't make sense to send to forAll?
  // property("Unit") = Prop forAll { (u: Unit) =>
  //   roundTrip(u)
  // }

  property("(Int, String)") = Prop forAll { (p: (Int, String)) =>
    roundTrip(p)
  }

  property("C") = Prop forAll { (i: Int) =>
    roundTrip(C(i))
  }

  property("D") = Prop forAll { (p: (Int, Double)) =>
    roundTrip(D(p._1, p._2))
  }

  property("E") = Prop forAll { (p: (Int, String)) =>
    roundTrip(E(p._1, p._2))
  }

  property("F") = Prop forAll { (p: (Int, Int)) =>
    roundTrip(F(p._1, C(p._2)))
  }

  property("G") = Prop forAll { (arr: Array[Int]) =>
    roundTripG(G(arr))
  }

  property("(Int, Array[Double])") = Prop forAll { (t: (Int, Array[Double])) =>
    val obj: Any = t
    val p = obj.pickle
    val up = p.unpickle[Any]
    val t2 = up.asInstanceOf[(Int, Array[Double])]
    t._1 == t2._1 && t._2.mkString(",") == t2._2.mkString(",")
  }
}

object RuntimeBinarySpec extends Properties("runtime-binary") {
  import binary._

  // there's no way to actually use any of our testing frameworks
  // to guarantee that the runtime picklers are being used
  // though by calling pickle on something that's statically
  // resolved to be Any will always trigger runtime pickling
  def roundTrip(obj: Any): Boolean = {
    val p = obj.pickle
    val up = p.unpickle[Any]
    obj == up
  }

  // there's no way to actually use any of our testing frameworks
  // to guarantee that the runtime picklers are being used
  // though by calling pickle on something that's statically
  // resolved to be Any will always trigger runtime pickling
  def roundTripG(obj: Any): Boolean = {
    val p = obj.pickle
    val up = p.unpickle[Any]
    obj.asInstanceOf[G].a.mkString(",") == up.asInstanceOf[G].a.mkString(",")
  }

  property("Int") = Prop forAll { (i: Int) =>
    roundTrip(i)
  }

  property("Double") = Prop forAll { (d: Double) =>
    roundTrip(d)
  }

  property("Long") = Prop forAll { (l: Long) =>
    roundTrip(l)
  }

  property("Char") = Prop forAll { (c: Char) =>
    roundTrip(c)
  }

  property("Float") = Prop forAll { (f: Float) =>
    roundTrip(f)
  }

  property("Boolean") = Prop forAll { (b: Boolean) =>
    roundTrip(b)
  }

  property("Short") = Prop forAll { (s: Short) =>
    roundTrip(s)
  }

  property("Byte") = Prop forAll { (b: Byte) =>
    roundTrip(b)
  }

  // It seems like Unit doesn't make sense to send to forAll?
  // property("Unit") = Prop forAll { (u: Unit) =>
  //   roundTrip(u)
  // }

  property("(Int, String)") = Prop forAll { (p: (Int, String)) =>
    roundTrip(p)
  }

  property("C") = Prop forAll { (i: Int) =>
    roundTrip(C(i))
  }

  property("D") = Prop forAll { (p: (Int, Double)) =>
    roundTrip(D(p._1, p._2))
  }

  property("E") = Prop forAll { (p: (Int, String)) =>
    roundTrip(E(p._1, p._2))
  }

  property("F") = Prop forAll { (p: (Int, Int)) =>
    roundTrip(F(p._1, C(p._2)))
  }

  property("G") = Prop forAll { (arr: Array[Int]) =>
    roundTripG(G(arr))
  }

  property("(Int, Array[Double])") = Prop forAll { (t: (Int, Array[Double])) =>
    val obj: Any = t
    val p = obj.pickle
    val up = p.unpickle[Any]
    val t2 = up.asInstanceOf[(Int, Array[Double])]
    t._1 == t2._1 && t._2.mkString(",") == t2._2.mkString(",")
  }
}


text:
1.5 (2022-06)
-------------
* Add Julian `decade` and `millennium` to `NonSI`.
* Rename `deka` prefix to `deca` in accordance with [international spelling](https://www.bipm.org/documents/20126/41483022/SI-Brochure-9.pdf/fcf090b2-04e6-88cc-1149-c3e029ad8232).
* Change `astronomicalUnit` symbol to lowercase (`au`).
* Remove `semigroups` dependency.
* Significant documentation improvements.

Thanks to @konsumlamm for many contributions!

1.4 (2021-05)
-------------
* Add `calorie` to `NonSI`.
* Remove deprecated `AutoDeriveTypeable` pragmas. This means that `Typable` instances are no provided on GHC prior to 8.2.

1.3 (2018-12)
-------------
* Breaking: Changed the `Show` instances for `UnitName`, `Unit`, `SQuantity` to use non-breaking spaces
  within unit names and between values and their units.
* Bumped exact-pi dependency to < 0.6.
* Added the dimensionless unit `percent`.
* Added dimensionless wrappers for `log1p`, `expm1`, `log1pexp`, and `log1mexp` from the `Floating` class.

1.2 (2018-11)
-------------
* Add `NoStarIsType` extension and import `Data.Kind.Type` for [GHC 8.6 compitbility](https://github.com/ghc-proposals/ghc-proposals/blob/05721788de9ab6538def68c3c2c9dec50c9f24a8/proposals/0020-no-type-in-type.rst). Abandon compatibility with GHC < 8.

1.1 (2018-03)
-------------
* Added `Semigroup` instances for [GHC 8.4 compatibility](https://ghc.haskell.org/trac/ghc/wiki/Migration/8.4#SemigroupMonoidsuperclasses).
* Breaking: Renamed `Root` type family to `NRoot`. Added `Sqrt` and `Cbrt` type
  synonyms. Added `sqrt` and `cbrt` for term level dimensions.
* Breaking: Changed `Numeric.Units.Dimensional.Prelude` to export dimensionally
  typed `signum`, `recip`, and `logBase` instead of the ones from `Prelude`.
* Breaking: Changed `Numeric.Units.Dimensional.Prelude` to export `(.)` and `id`
  from `Control.Category` instead of from `Prelude`.
* Breaking: Created a `product` function which take the product of a foldable structure of
  `Dimensionless` values. Exported this `product` function from Numeric.Units.Dimensional.Prelude
  instead of the one from `Prelude`.
* Breaking: Changed the `HasDimension` typeclass to require an instance of the new
  `HasDynamicDimension` typeclass.
* Breaking: Added operators for `AnyUnit` to the Numeric.Units.Dimensional.Dynamic
  module which may cause name collisions.
* Breaking: Added dynamic versions of `(*~)`, `(/~)`, and `siUnit` to the Numeric.Units.Dimensional.Dynamic
  module which may cause name collisions.
* Breaking: Removed exports of `nMeter`, `nSecond`, `kilo`, etc from Numeric.Units.Dimensional.UnitNames.
  Access these instead by inspecting the relevant units or prefixes.
* Breaking: Generalized the type of `dimensionlessLength` from
  `(Num a, Foldable f) => f (Dimensional v d a) -> Dimensionless a)` to
  `(Num a, Foldable f) => f b -> Dimensionless a`. This provides a weaker constraint on the type `a`
  and may result in ambiguous types in code that depends on the former less general type.
* Fixed a bug in the definition of the `inHg_NIST`.
* Fixed a bug in the interchange name of the Dalton.
* Added units for the US survey foot, yard, inch, mil, and mile.
* Added the short ton as a unit of mass.
* Clarified that the UCUM acre is based on the US survey foot.
* Added a version of the acre based on the international foot.
* Added `Data`, `Generic`, `Typeable` and `NFData` instances for many ancillary types.
* Added `unQuantity` to the Coercion module to ease unwrapping without
  introducing ambiguous type variables.
* Created explicit representation of metric `Prefix`es.
* Added a multiplicative `Monoid` instance for `AnyQuantity` and for `AnyUnit`.
* Added the `DynQuantity` type to represent possibly valid quantities of statically
  unknown dimension, suitable for performing arithmetic with such quantities.
* Added `nroot` function for term-level dimensions.
* Added the Numeric.Units.Dimensional.Float module with convenient wrappers around functions
  from RealFloat and IEEE for inspecting floating point quantities.
* Added an `AEq` instance for `Quantity`.
* Added `Eq1` and `Ord1` instances for `Quantity`.
* Exposed the name of an 'AnyUnit' without promoting it to a 'Unit' first.
* Exposed a way to convert atomic 'UnitName's back into 'NameAtom's.
* Added the `btu`, a unit of energy.
* Added the `gauss`, a unit of magnetic flux density.
* Added the `angstrom`, a unit of length.
* Relocated git repository to https://github.com/bjornbm/dimensional

1.0.1.3 (2016-09)
-----------------
* Fixed an issue with applying metric prefixes to units with non-rational conversion factors.

1.0.1.2 (2016-05)
-----------------
* Support for GHC 8.0.1-rc4, avoiding GHC Trac issue 12026.
* Added support for stack.

1.0.1.1 (2015-11)
-----------------
* Improved example in readme.

1.0.1.0 (2015-11)
-----------------
* Added Numeric.Units.Dimensional.Coercion module.
* Bumped exact-pi dependency to < 0.5.
* Restored changelog.
* Addressed issues with documentation.

1.0.0.0 (2015-11)
-----------------
* Changed to DataKinds and ClosedTypeFamilies encoding of dimensions.
* Added names and exact values to `Unit`s.
* Added `AnyUnit` and `AnyQuantity` for quantities whose dimension is statically unknown.
* Added Storable and Unbox instances for `Quantity`.
* Added dimensionally-polymorphic `siUnit` for the coherent SI base unit of any dimension.
* Added some additional units.

0.13.0.2 (2015-04)
------------------
*  Corrected definition of lumen.

0.13.0.1 (2014-09)
------------------
*  Bumped time dependency to < 1.6.

0.13 (2014-02)
--------------
*  Bump major version (should have been done in previous version).

0.12.3 (2014-02)
----------------
*  Bump numtype dependency to 1.1 (GHC 7.8.1 compatibility fix).
*  Added `Torque`.
*  Added D.. for the type synonym quantities (e.g., `Angle`).

0.12.2 (2013-11)
----------------
*  Added `FirstMassMoment`, `MomentOfInertia`, `AngularMomentum`.
*  Improved unit numerics.

0.12.1 (2013-07)
----------------
*  Typeable Dimensionals.

0.12 (2013-06)
--------------
*  Polymorphic `_0` (closes issue 39).
*  Added `astronomicalUnit`.
*  Added imperial volume units.
*  Added 'mil' (=inch/1000).
*  Added [`tau`][3].
*  Added `KinematicViscosity`.

[3]: https://tauday.com/tau-manifesto

0.10.1.2 (2011-09)
------------------
*  Bumped time dependency to < 1.5.

0.10.1.2 (2011-08)
------------------
*  Bumped time dependency to < 1.4.

0.10.1 (2011-08)
----------------
GHC 7.2.1 compatibility fix:

*  Increased CGS context-stack to 30.

0.10 (2011-05)
--------------
See the [announcement][2].

[2]: https://flygdynamikern.blogspot.se/2011/05/announce-dimensional-010.html

0.9 (2011-04)
-------------
See the [announcement][1].

[1]: https://flygdynamikern.blogspot.se/2011/04/announce-dimensional-09.html


text:
#ifndef __mDNSUNP_h
#define __mDNSUNP_h

#include <sys/types.h>
#include <sys/socket.h>
#include <net/if.h>
#include <netinet/in.h>

#ifdef HAVE_LINUX
#include <linux/socket.h>
#define IPV6_2292_PKTINFO  IPV6_2292PKTINFO
#define IPV6_2292_HOPLIMIT IPV6_2292HOPLIMIT
#else
// The following are the supported non-linux posix OSes -
// netbsd, freebsd and openbsd.
#if HAVE_IPV6
#define IPV6_2292_PKTINFO  19
#define IPV6_2292_HOPLIMIT 20
#endif
#endif

#ifdef  __cplusplus
    extern "C" {
#endif

#ifdef NOT_HAVE_SOCKLEN_T
    typedef unsigned int socklen_t;
#endif

#if !defined(_SS_MAXSIZE) && !defined(__ANDROID__)
#if HAVE_IPV6
#define sockaddr_storage sockaddr_in6
#else
#define sockaddr_storage sockaddr
#endif // HAVE_IPV6
#endif // !defined(_SS_MAXSIZE) && !defined(__ANDROID__)

#ifndef NOT_HAVE_SA_LEN
#define GET_SA_LEN(X) (sizeof(struct sockaddr) > ((struct sockaddr*)&(X))->sa_len ? \
                       sizeof(struct sockaddr) : ((struct sockaddr*)&(X))->sa_len   )
#elif HAVE_IPV6
#define GET_SA_LEN(X) (((struct sockaddr*)&(X))->sa_family == AF_INET  ? sizeof(struct sockaddr_in) : \
                       ((struct sockaddr*)&(X))->sa_family == AF_INET6 ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr))
#else
#define GET_SA_LEN(X) (((struct sockaddr*)&(X))->sa_family == AF_INET ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr))
#endif

#define IFI_NAME    16          /* same as IFNAMSIZ in <net/if.h> */
#define IFI_HADDR    8          /* allow for 64-bit EUI-64 in future */

// Renamed from my_in_pktinfo because in_pktinfo is used by Linux.

struct my_in_pktinfo {
    struct sockaddr_storage ipi_addr;
    int                     ipi_ifindex;            /* received interface index */
    char                    ipi_ifname[IFI_NAME];   /* received interface name  */
};

/* From the text (Stevens, section 20.2): */
/* 'As an example of recvmsg we will write a function named recvfrom_flags that */
/* is similar to recvfrom but also returns: */
/*	1. the returned msg_flags value, */
/*	2. the destination addres of the received datagram (from the IP_RECVDSTADDR socket option, and */
/*	3. the index of the interface on which the datagram was received (the IP_RECVIF socket option).' */
extern ssize_t recvfrom_flags(int fd, void *ptr, size_t nbytes, int *flagsp,
               struct sockaddr *sa, socklen_t *salenptr, struct my_in_pktinfo *pktp, u_char *ttl);

struct ifi_info {
  char    ifi_name[IFI_NAME];   /* interface name, null terminated */
  u_char  ifi_haddr[IFI_HADDR]; /* hardware address */
  u_short ifi_hlen;             /* #bytes in hardware address: 0, 6, 8 */
  short   ifi_flags;            /* IFF_xxx constants from <net/if.h> */
  short   ifi_myflags;          /* our own IFI_xxx flags */
  int     ifi_index;            /* interface index */
  struct sockaddr  *ifi_addr;   /* primary address */
  struct sockaddr  *ifi_netmask;
  struct sockaddr  *ifi_brdaddr;/* broadcast address */
  struct sockaddr  *ifi_dstaddr;/* destination address */
  struct ifi_info  *ifi_next;   /* next of these structures */
};

#if defined(AF_INET6) && HAVE_IPV6 && HAVE_LINUX
#define PROC_IFINET6_PATH "/proc/net/if_inet6"
extern struct ifi_info  *get_ifi_info_linuxv6(int family, int doaliases);
#endif

#if defined(AF_INET6) && HAVE_IPV6
#define INET6_ADDRSTRLEN 46 /*Maximum length of IPv6 address */
#endif

#define IFI_ALIAS   1           /* ifi_addr is an alias */

/* From the text (Stevens, section 16.6): */
/* 'Since many programs need to know all the interfaces on a system, we will develop a */
/* function of our own named get_ifi_info that returns a linked list of structures, one */
/* for each interface that is currently "up."' */
extern struct ifi_info  *get_ifi_info(int family, int doaliases);

/* 'The free_ifi_info function, which takes a pointer that was */
/* returned by get_ifi_info and frees all the dynamic memory.' */
extern void             free_ifi_info(struct ifi_info *);

#ifdef NOT_HAVE_DAEMON
extern int daemon(int nochdir, int noclose);
#endif

#ifdef  __cplusplus
    }
#endif

#endif


text:
package Utility;

import java.awt.Font;
import java.awt.FontFormatException;
import java.io.IOException;
import java.net.URL;

import javax.swing.ImageIcon;

public class Utils
{

	public static String getFileExtension(String name) {
	int pointIndex = name.lastIndexOf(".");

	if (pointIndex == -1)
	{
		return null;
	}

	if (pointIndex == name.length() - 1) {
		return null;
	}

	return name.substring(pointIndex + 1, name.length());

	}
	// *************************************************************************************************************************
	public static ImageIcon createIcon(String path) {
		URL url = System.class.getResource(path);

		if (url == null) {
			System.err.println("Unable to load image: " + path);
		}

		ImageIcon icon = new ImageIcon(url);

		return icon;
	}
	// *************************************************************************************************************************
	public static Font createFont(String path) {
		URL url = System.class.getResource(path);

		if (url == null) {
			System.err.println("Unable to load font: " + path);
		}

		Font font = null;
		try {
			font = Font.createFont(Font.TRUETYPE_FONT, url.openStream());
		} catch (FontFormatException e) {
			System.err.println("Bad format in font file: " + path);
		} catch (IOException e) {
			System.out.println("Unable to read font file: " + path);
		}

		return font;
	}
}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:id="@+id/Background"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="@dimen/activity_vertical_margin"
    tools:context=".MyActivity"
    tools:ignore="MergeRootFrame">

    <com.google.android.gms.ads.AdView
        android:id="@+id/ad_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        ads:adSize="BANNER"
        ads:adUnitId="@string/banner_ad_unit_id" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/DoButton"
        android:layout_centerHorizontal="true"/>

</RelativeLayout>
<!-- From: file:/Users/akin8529/Documents/Android%20Workspace/AdMobBanner/app/src/main/res/layout/activity_my.xml -->


text:
import time
print('Sleeping for 60 seconds')
time.sleep(60)
print('Timeout, this job should have been cancelled within 60 seconds !')


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

<title>Asset</title>
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

nxt

Class Asset

java.lang.Object

nxt.Asset

public final class Asset
extends java.lang.Object

Method Summary

Methods

Modifier and Type
Method and Description

java.lang.Long
getAccountId()

static java.util.Collection<Asset>
getAllAssets()

static Asset
getAsset(java.lang.Long id)

static Asset
getAsset(java.lang.String name)

java.lang.String
getDescription()

java.lang.Long
getId()

java.lang.String
getName()

int
getQuantity()

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Method Detail

getAllAssets

public static java.util.Collection<Asset> getAllAssets()

getAsset

public static Asset getAsset(java.lang.Long id)

getAsset

public static Asset getAsset(java.lang.String name)

getId

public java.lang.Long getId()

getAccountId

public java.lang.Long getAccountId()

getName

public java.lang.String getName()

getDescription

public java.lang.String getDescription()

getQuantity

public int getQuantity()

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
jQuery.sap.declare("sap.ui.codeeditor.sample.CodeEditor.Component");

sap.ui.core.UIComponent.extend("sap.ui.codeeditor.sample.CodeEditor.Component", {

	metadata: {
		rootView: "sap.ui.codeeditor.sample.CodeEditor.CodeEditor",
		dependencies: {
			libs: [ "sap.ui.codeeditor"]
		},
		config: {
			sample: {
				stretch: true,
				files: [
					"CodeEditor.view.xml"
				]
			}
		}
	}
});


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Didissandra johorica Ridley

### Remarks
null


text:
// TypeScript for Meteor
// Copyright 2015-2016 Oliver Kuckertz <oliver.kuckertz@mologie.de>
// Refer to COPYING for license information.

// TODO:
// implement serializing/deserializing document cache for faster startup
// update readme, explain how this is not the big other typescript compiler plugin
//  - faster, more up-to-date, minimalistic, input AST caching, package support, mixing different
//    file types (TS, JS), source map support
//  - document that export = null is required for switching to local scope mode

var fs     = Plugin.fs;
var path   = Plugin.path;
var meteor = this;
var crypto = Npm.require("crypto");
var _      = Npm.require("lodash");

const ENABLE_AGGRESSIVE_CACHING = false; // ignore requests from Meteor to invalidate the cache

function fileExists(path) {
    try {
        fs.statSync(path);
        return true;
    }
    catch (err) {
        return false;
    }
}

class TSCompiler {
    constructor() {
        this.cache = null;
    }

    setDiskCacheDirectory(diskCache) {
        // Meteor calls setDiskCacheDirectory immediately after creating the TSCompiler class.
        // Some Meteor plugins have the same check, so this will probably last.
        if (this.diskCache) {
            throw Error("setDiskCacheDirectory called twice");
        }
        this.diskCache = diskCache;
        this.loadDocumentCache();
    }

    loadDocumentCache() {
        // Reuse the previous cache if one is available. Minor hack: Meteor's disk cache path is
        // is for testing if the cache should be invalidated. The disk cache path will change when
        // this plugin updates or dependencies of the application change.
        this.cache = TSCompiler.acquireCache(this.diskCache);
        this.ts = (this.cache.ts || (this.cache.ts = Npm.require("typescript")));
        this.documentRegistry = (this.cache.documentRegistry
            || (this.cache.documentRegistry = this.ts.createDocumentRegistry()));
        this.archCache = (this.cache.archCache || (this.cache.archCache = {}));

        // TODO populate documentRegistry from disk for faster startup
    }

    saveDocumentCache() {
        // TODO serialize documentRegistry to disk
    }

    processFilesForTarget(inputFiles) {
        // Sanity check
        if (!this.cache) {
            throw Error("processFilesForTarget called before setDiskCacheDirectory");
        }

        // Process each architecture
        // XXX Currently, this is redundant, because processFilesForTarget is called once for each
        // architecture.
        let filesPerArch = _.groupBy(inputFiles, (file) => file.getArch());
        for (let arch of Object.keys(filesPerArch)) {
            if (!(arch in this.archCache)) {
                this.archCache[arch] = {};
            }
            this.processFilesForArch(arch, this.archCache[arch], filesPerArch[arch]);
        }

        // Sync cache to disk
        this.saveDocumentCache();
    }

    processFilesForArch(arch, archCache, inputFiles) {
        var ts = this.ts;

        // File index for reverse lookups
        var allFiles = _.keyBy(inputFiles, (file) => {
            let packageName = file.getPackageName();
            let filePrefix = "";
            if (packageName) {
                filePrefix = "packages/" + packageName.replace(":", "/") + "/";
            }
            return filePrefix + file.getPathInPackage();
        });

        // Grab and evaluate tsconfig.json from the application root
        // Embedded packages will inherit settings from the application's tsconfig.json
        let tsconfig = {
            compilerOptions: {},
            files: [],
            exclude: []
        };
        let configFiles = inputFiles.filter(TSCompiler.isConfigFile);
        if (configFiles.length > 0) {
            var configFile = configFiles[0];
            let configText = configFile.getContentsAsString();
            let loadResult = ts.parseConfigFileTextToJson("tsconfig.json", configText);

            if (loadResult.error) {
                let e = loadResult.error;
                let message = ts.flattenDiagnosticMessageText(e.messageText, "\n");
                let { line, character } = e.file.getLineAndCharacterOfPosition(e.start);
                configFile.error({
                    message: message,
                    line: line,
                    column: character
                });
            }
            else if (loadResult.config) {
                let unprocessedConfig = loadResult.config;

                if (unprocessedConfig.compilerOptions) {
                    tsconfig.compilerOptions = ts.convertCompilerOptionsFromJson(
                        ts.optionDeclarations, unprocessedConfig.compilerOptions);
                }

                if (unprocessedConfig.files) {
                    // Add all definition files from tsconfig.json to the compiliation context
                    // This allows omitting a project-wide reference line which would otherwise be
                    // required for each file, while at the same time making editors that depend on
                    // tsconfig.json happy.
                    tsconfig.files = unprocessedConfig.files.filter((fileName) => {
                        // Test if the file is available in the current context (client or server)
                        let inputFile = allFiles[fileName];
                        if (inputFile) {
                            return TSCompiler.isDefinitionFile(inputFile);
                        }

                        // Silently skip loading server-only scripts on the client and client-only
                        // scripts on the server.
                        if (fileName.startsWith("server/") || fileName.startsWith("client/")) {
                            if (!fileExists(fileName)) {
                                configFile.error({
                                    message: "Explicitly referenced file '" + fileName + "' does "
                                        + "not exist."
                                });
                            }
                            return false;
                        }

                        // The file is not part of the Meteor directory. Assume that the user made
                        // a mistake and complain accordingly.
                        configFile.error({
                            message: "Explicitly referenced file '" + fileName + "' was not "
                                + "loaded through Meteor. If this was intentional, place a "
                                + "symlink to the external file into your Meteor project "
                                + "directory."
                        });
                        return false;
                    });
                }

                if (unprocessedConfig.exclude) {
                    // XXX Check that all to-be-excluded files exist here?
                    tsconfig.exclude = unprocessedConfig.exclude;
                }
            }
        }

        // Process files per package
        // Meteor performs garbage collection automatically by destryoing TSCompiler if the list
        // of embedded packages changes.
        let filesPerPackage = _.groupBy(inputFiles, (file) => file.getPackageName() || "");
        for (let packageName of Object.keys(filesPerPackage)) {
            if (!(packageName in archCache)) {
                archCache[packageName] = {};
            }
            this.processFilesForPackage(packageName, archCache[packageName], arch,
                filesPerPackage[packageName], allFiles, tsconfig);
        }
    }

    processFilesForPackage(packageName, packageCache, arch, inputFiles, allFiles, tsconfig) {
        var ts = this.ts;

        // Heuristics for better embedded package support
        // By rebasing all paths into the package's real directory, referencing files outside of
        // the package becomes possible. Name conflicts between package files and application files
        // are avoided.
        var filePrefix = "";
        if (packageName) {
            let packageFileName = packageName.replace(":", "_");
            filePrefix = "packages/" + packageFileName + "/";
        }

        // For log messages
        let friendlyPackageName = packageName ? `package ${packageName}` : "application";

        // Collect files which need compiling
        var excludedFilesIndex = _.keyBy(tsconfig.exclude, _.identity);
        var rootFiles = [].concat(tsconfig.files);
        inputFiles.forEach((file) => {
            // Don't compile tsconfig.json
            if (TSCompiler.isConfigFile(file)) {
                return;
            }

            // Don't compile files in or under tsconfig.json's excluded files/directories
            // XXX This will break when TypeScript adds globs to tsconfig.json, see
            //     https://github.com/Microsoft/TypeScript/issues/1927
            let fileName = filePrefix + file.getPathInPackage();
            let fileComponents = fileName.split("/");
            for (let i = 0; i < fileComponents.length; i++) {
                if (fileComponents.slice(0, i + 1).join("/") in excludedFilesIndex) {
                    // File or the file's directory have been excluded
                    return;
                }
            }

            rootFiles.push(fileName);
        });

        // Process configuration
        // Syntax change test taken from TypeScript's src/services/services.ts
        var oldSettings = packageCache.program && packageCache.program.getCompilerOptions();
        var newSettings = loadPackageConfig();
        var newSettingsChangeSyntax = oldSettings &&
            (oldSettings.target !== newSettings.target ||
             oldSettings.module !== newSettings.module ||
             oldSettings.noResolve !== newSettings.noResolve ||
             oldSettings.jsx !== newSettings.jsx);

        // Compiler host specific to this package and architecture
        var compilerOutput = {};
        var compilerHost = {
            getSourceFile: (fileName) => {
                let script = findScript(fileName);
                if (!script) {
                    return undefined;
                }

                // Attempt to get or update an existing cache entry
                if (!newSettingsChangeSyntax) {
                    let oldProgram = packageCache.program;
                    let oldSourceFile = oldProgram && oldProgram.getSourceFile(fileName);
                    if (oldSourceFile) {
                        return this.documentRegistry.updateDocument(fileName, newSettings,
                            script.snapshot, script.version);
                    }
                }

                // Create a new cache entry
                return this.documentRegistry.acquireDocument(fileName, newSettings,
                    script.snapshot, script.version);
            },

            getCanonicalFileName: (fileName) => {
                return fileName;
            },

            useCaseSensitiveFileNames: () => {
                return false;
            },

            getNewLine: () => {
                return "\n";
            },

            getDefaultLibFileName: (options) => {
                return Plugin.convertToStandardPath(ts.getDefaultLibFilePath(options));
            },

            getCurrentDirectory: () => {
                return filePrefix;
            },

            fileExists: (fileName) => {
                // XXX Use of deprecated method
                // Is this function required by the TypeScript compiler at all?
                return !!allFiles[fileName] || fileExists(fileName);
            },

            writeFile: (fileName, data, writeByteOrderMark) => {
                compilerOutput[fileName] = data;
            },

            readFile: (fileName) => {
                // Check the Meteor-provided file list first
                if (allFiles[fileName]) {
                    return allFiles[fileName].getContentsAsString();
                }

                // Fall back to reading relative to the working directory, whereever that is
                return fs.readFileSync(filePath, {encoding: "utf8"});
            }
        };

        // Create a program containing this package's files
        // Two different cache layers are applied here: TypeScript reuses parts of the old program
        // (if any), and the compiler host provides ASTs from the document registry if available.
        var oldProgram = packageCache.program || null;
        var newProgram = ts.createProgram(rootFiles, newSettings, compilerHost, oldProgram);

        // Release files which are available in oldProgram but not in newProgram from the cache.
        // Logic from TypeScript's src/services/services.ts.
        if (oldProgram) {
            let oldSourceFiles = oldProgram.getSourceFiles();
            for (let oldSourceFile of oldSourceFiles) {
                let fileName = oldSourceFile.fileName;
                if (!newProgram.getSourceFiles(fileName) || newSettingsChangeSyntax) {
                    this.documentRegistry.releaseDocument(fileName, oldSettings);
                }
            }
        }

        // Update cache
        packageCache.program = newProgram;

        // Compile the package. The compiler host's writeFile method is called here.
        let emitResult = newProgram.emit();
        let allDiagnostics = ts.getPreEmitDiagnostics(newProgram).concat(emitResult.diagnostics);

        // Complain if there are any errors
        allDiagnostics.forEach(logError);

        // Register compiler output with Meteor
        for (let fileName of rootFiles) {
            let compiledFileName = fileName.slice(0, -3) + ".js";
            let sourceMapFileName = compiledFileName + ".map";
            let inputFile = allFiles[fileName];

            if (!compilerOutput[compiledFileName]) {
                continue;
            }

            // Drop the packages/<name>/ prefix
            let generatedFileName = inputFile.getPathInPackage().slice(0, -3) + ".js";

            // Get ES3/5 compiler output
            let data = postProcessJs(inputFile, compilerOutput[compiledFileName]);

            // Get source map
            let sourceMap = compilerOutput[sourceMapFileName];
            if (sourceMap) {
                sourceMap = JSON.parse(sourceMap);
                sourceMap.generatedFile = "/" + generatedFileName;
                sourceMap.sources = [inputFile.getDisplayPath()];
            }

            inputFile.addJavaScript({
                sourcePath: inputFile.getPathInPackage(),
                path: generatedFileName,
                data,
                sourceMap,
            });
        }

        function postProcessJs(inputFile, code) {
            // Heuristics for providing a more helpful error message than TypeScript's default
            // 'duplicate identifier' errors which may occur when not using any import or export
            // statements.
            // XXX Remove this test once TypeScript provides a compiler option which controls the
            // default scope of files.
            if (code.indexOf("exports.") == -1 && code.indexOf("require(") == -1) {
                inputFile.error({
                    message: "File does not have a top-level import or export statement. "
                        + "Did you forget to 'export default null'?"
                });
                return code;
            }

            // Strip the source map reference - Meteor assigns source maps using HTTP headers
            code = code.replace(/^\/\/# sourceMappingURL=.*$/m, "");

            return code;
        }

        function loadPackageConfig() {
            let suggestedOptions = {
                charset: "utf8",
                preverseConstEnums: true,
                module: ts.ModuleKind.CommonJS
            };

            let enforcedOptions = {
                declaration: false,
                diagnostics: true,
                emitBOM: false,
                inlineSourceMap: false,
                inlineSources: true,
                mapRoot: "",
                sourceMap: true,
                noEmit: false,
                noEmitHelpers: false,
                noEmitOnError: true,
                out: undefined,
                outFile: undefined,
                target: (arch == "web.browser") ? ts.ScriptTarget.ES3 : ts.ScriptTarget.ES5
            };

            return _.assign(
                {},
                ts.getDefaultCompilerOptions(),
                suggestedOptions,
                tsconfig.compilerOptions,
                enforcedOptions
            );
        }

        function findScript(fileName) {
            let contents;

            if (allFiles[fileName]) {
                contents = allFiles[fileName].getContentsAsString();
            }
            else {
                // Read script from disk
                try {
                    // XXX Cache the result of readFileSync until processFilesForTarget returns
                    contents = fs.readFileSync(fileName, {encoding: "utf8"});
                }
                catch (e) {
                    // XXX Test for ENOENT and rethrow otherwise?
                    return undefined;
                }
            }

            // Use a custom checksum for synchronization of the Meteor file cache and of files read
            // from disk on demand. We unfortunately cannot rely on inputFile.getSourceHash()
            // because its algorithm is not documented.
            let version = crypto.createHash("sha1").update(contents).digest("hex");

            return {
                snapshot: ts.ScriptSnapshot.fromString(contents),
                version: version
            };
        }

        function logError(e) {
            // Small inconvenience: Meteor wants us to assign errors to inputFile objects, but
            // that's really not always possible. TypeScript files may reference arbitrary files on
            // the file system (at least lib.d.ts). Throw an ugly error in such cases.
            let message = ts.flattenDiagnosticMessageText(e.messageText, "\n");
            if (e.file) {
                let { line, character } = e.file.getLineAndCharacterOfPosition(e.start);
                let inputFile = allFiles[e.file.fileName];
                if (inputFile) {
                    inputFile.error({
                        message: message,
                        line: line,
                        column: character
                    });
                }
                else {
                    throw Error(`TypeScript error while compiling ${friendlyPackageName} at `
                        + `${e.file.fileName} (line ${line}:${character}): ${message}`);
                }
            }
            else {
                throw Error(`TypeScript error while compiling ${friendlyPackageName}: ${message}`);
            }
        }
    }

    static isDefinitionFile(inputFile) {
        return inputFile.getExtension() == "d.ts";
    }

    static isConfigFile(inputFile) {
        return inputFile.getPathInPackage() == "tsconfig.json";
    }

    // Meteor will recreate an instance of TSCompiler each time the application is rebuilt.
    // In order to persist the cache across rebuilds in memory, a reference to the cache is stored
    // with the global context.
    static acquireCache(token) {
        let cache = meteor.__typescriptCache;
        if (cache && (cache.token == token || ENABLE_AGGRESSIVE_CACHING)) {
            return cache;
        }
        meteor.__typescriptCache = {};
        meteor.__typescriptCache.token = token;
        return meteor.__typescriptCache;
    }
}

Plugin.registerCompiler({
    extensions: [
        "d.ts", // TypeScript definition files (separate for getExtension() tests)
        "ts",   // TypeScript source files
        "tsx"   // React TypeScript files
    ],
    filenames: [
        "tsconfig.json"
    ]
}, function () {
    return new TSCompiler();
});

/* vim: set ts=4 sw=4 sts=4 et : */


text:
package opencsp.csta.types;

import opencsp.csta.xml.CSTAXmlSerializable;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import java.util.List;

public class CrossReferenceId implements CSTAXmlSerializable {
    private int crossReferenceId;

    public CrossReferenceId(int id) {
        this.crossReferenceId = id;
    }

    public String toString() {
        return Integer.toString(crossReferenceId);
    }

    public Element toXmlElement(Document doc, String tagName) {
        Element e = doc.createElement(tagName);
        e.setTextContent(Integer.toString(crossReferenceId));
        return e;
    }

    public Element toXmlElement(Document doc) {
        return toXmlElement(doc, "monitorCrossRefID");
    }

    @Override
    public boolean equals(Object other) {
        return ((CrossReferenceId)other).crossReferenceId == crossReferenceId;
    }

    @Override
    public int hashCode() {
        return Integer.hashCode(crossReferenceId);
    }
}