text:
import argparse
import os
from multiprocessing import Pool
import logging
from distutils.util import strtobool

import tensorflow as tf

from generic.data_provider.iterator import Iterator
from generic.tf_utils.evaluator import Evaluator
from generic.tf_utils.optimizer import create_optimizer
from generic.data_provider.image_loader import get_img_builder
from generic.utils.config import load_config, get_config_from_xp

from guesswhat.models.oracle.oracle_network import OracleNetwork
from guesswhat.models.qgen.qgen_lstm_network import QGenNetworkLSTM
from guesswhat.models.guesser.guesser_network import GuesserNetwork
from guesswhat.models.looper.basic_looper import BasicLooper

from guesswhat.models.qgen.qgen_wrapper import QGenWrapper
from guesswhat.models.oracle.oracle_wrapper import OracleWrapper
from guesswhat.models.guesser.guesser_wrapper import GuesserWrapper

from guesswhat.data_provider.guesswhat_dataset import Dataset
from guesswhat.data_provider.looper_batchifier import LooperBatchifier
from guesswhat.data_provider.guesswhat_tokenizer import GWTokenizer

from guesswhat.train.utils import test_model, compute_qgen_accuracy

if __name__ == '__main__':

    parser = argparse.ArgumentParser('Question generator (policy gradient baseline))')

    parser.add_argument("-data_dir", type=str, required=True, help="Directory with data")
    parser.add_argument("-exp_dir", type=str, required=True, help="Directory in which experiments are stored")
    parser.add_argument("-img_dir", type=str, help='Directory with images')
    parser.add_argument("-crop_dir", type=str, help='Directory with images')
    parser.add_argument("-config", type=str, required=True, help='Config file')
    parser.add_argument("-dict_file", type=str, default="dict.json", help="Dictionary file name")

    parser.add_argument("-networks_dir", type=str, help="Directory with pretrained networks")
    parser.add_argument("-oracle_identifier", type=str, required=True , help='Oracle identifier')  # Use checkpoint id instead?
    parser.add_argument("-qgen_identifier", type=str, required=True, help='Qgen identifier')
    parser.add_argument("-guesser_identifier", type=str, required=True, help='Guesser identifier')

    parser.add_argument("-continue_exp", type=bool, default=True, help="Continue previously started experiment?")
    #parser.add_argument("-from_checkpoint", type=str, help="Start from checkpoint?")
    parser.add_argument("-skip_training",  type=lambda x: bool(strtobool(x)), default="False", help="Start from checkpoint?")
    parser.add_argument("-evaluate_all", type=lambda x: bool(strtobool(x)), default="False", help="Evaluate sampling, greedy and BeamSearch?")  #TODO use an input list
    parser.add_argument("-store_games", type=lambda x: bool(strtobool(x)), default="True", help="Should we dump the game at evaluation times")

    parser.add_argument("-gpu_ratio", type=float, default=0.95, help="How muany GPU ram is required? (ratio)")
    parser.add_argument("-no_thread", type=int, default=1, help="No thread to load batch")

    args = parser.parse_args()

    loop_config, exp_identifier, save_path = load_config(args.config, args.exp_dir)

    # Load all  networks configs
    oracle_config = get_config_from_xp(os.path.join(args.networks_dir, "oracle"), args.oracle_identifier)
    guesser_config = get_config_from_xp(os.path.join(args.networks_dir, "guesser"), args.guesser_identifier)
    qgen_config = get_config_from_xp(os.path.join(args.networks_dir, "qgen"), args.qgen_identifier)

    logger = logging.getLogger()

    ###############################
    #  LOAD DATA
    #############################

    # Load image
    logger.info('Loading images..')
    image_builder = get_img_builder(qgen_config['model']['image'], args.img_dir)

    crop_builder = None
    if oracle_config['inputs'].get('crop', False):
        logger.info('Loading crops..')
        crop_builder = get_img_builder(oracle_config['model']['crop'], args.crop_dir, is_crop=True)

    # Load data
    logger.info('Loading data..')
    trainset = Dataset(args.data_dir, "train", image_builder, crop_builder)
    validset = Dataset(args.data_dir, "valid", image_builder, crop_builder)
    testset = Dataset(args.data_dir, "test", image_builder, crop_builder)

    # Load dictionary
    logger.info('Loading dictionary..')
    tokenizer = GWTokenizer(os.path.join(args.data_dir, args.dict_file))

    ###############################
    #  LOAD NETWORKS
    #############################

    logger.info('Building networks..')

    qgen_network = QGenNetworkLSTM(qgen_config["model"], num_words=tokenizer.no_words, policy_gradient=True)
    qgen_var = [v for v in tf.global_variables() if "qgen" in v.name] # and 'rl_baseline' not in v.name
    qgen_saver = tf.train.Saver(var_list=qgen_var)

    oracle_network = OracleNetwork(oracle_config, num_words=tokenizer.no_words)
    oracle_var = [v for v in tf.global_variables() if "oracle" in v.name]
    oracle_saver = tf.train.Saver(var_list=oracle_var)

    guesser_network = GuesserNetwork(guesser_config["model"], num_words=tokenizer.no_words)
    guesser_var = [v for v in tf.global_variables() if "guesser" in v.name]
    guesser_saver = tf.train.Saver(var_list=guesser_var)

    loop_saver = tf.train.Saver(allow_empty=False)

    ###############################
    #  REINFORCE OPTIMIZER
    #############################

    logger.info('Building optimizer..')

    pg_variables = [v for v in tf.trainable_variables() if "qgen" in v.name and 'rl_baseline' not in v.name]
    baseline_variables = [v for v in tf.trainable_variables() if "qgen" in v.name and 'rl_baseline' in v.name]

    pg_optimize, _ = create_optimizer(qgen_network, loop_config["optimizer"],
                                   var_list=pg_variables,
                                   optim_cst=tf.train.GradientDescentOptimizer,
                                   loss=qgen_network.policy_gradient_loss)
    baseline_optimize, _= create_optimizer(qgen_network, loop_config["optimizer"],
                                        var_list=baseline_variables,
                                        optim_cst=tf.train.GradientDescentOptimizer,
                                        apply_update_ops=False,
                                        loss=qgen_network.baseline_loss)

    optimizer = [pg_optimize, baseline_optimize]

    ###############################
    #  START TRAINING
    #############################

    # Load config
    batch_size = loop_config['optimizer']['batch_size']
    no_epoch = loop_config["optimizer"]["no_epoch"]

    mode_to_evaluate = ["greedy"]
    if args.evaluate_all:
        mode_to_evaluate = ["greedy", "sampling", "beam_search"]

    # create a saver to store/load checkpoint
    saver = tf.train.Saver()

    # CPU/GPU option
    cpu_pool = Pool(args.no_thread, maxtasksperchild=1000)
    gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=args.gpu_ratio)

    with tf.Session(config=tf.ConfigProto(gpu_options=gpu_options)) as sess:

        ###############################
        #  LOAD PRE-TRAINED NETWORK
        #############################

        sess.run(tf.global_variables_initializer())
        if args.continue_exp: # TODO only reload qgen ckpt
            qgen_saver.restore(sess, save_path.format('params.ckpt'))
        else:
            qgen_var_supervized = [v for v in tf.global_variables() if "qgen" in v.name and 'rl_baseline' not in v.name]
            qgen_loader_supervized = tf.train.Saver(var_list=qgen_var_supervized)
            qgen_loader_supervized.restore(sess, os.path.join(args.networks_dir, 'qgen', args.qgen_identifier, 'params.ckpt'))

        oracle_saver.restore(sess, os.path.join(args.networks_dir, 'oracle', args.oracle_identifier, 'params.ckpt'))
        guesser_saver.restore(sess, os.path.join(args.networks_dir, 'guesser', args.guesser_identifier, 'params.ckpt'))

        # create training tools
        loop_sources = qgen_network.get_sources(sess)
        logger.info("Sources: " + ', '.join(loop_sources))

        evaluator = Evaluator(loop_sources, qgen_network.scope_name, network=qgen_network, tokenizer=tokenizer)

        train_batchifier = LooperBatchifier(tokenizer,  generate_new_games=True)
        eval_batchifier = LooperBatchifier(tokenizer, generate_new_games=False)

        # Initialize the looper to eval/train the game-simulation

        oracle_wrapper = OracleWrapper(oracle_network, tokenizer)
        guesser_wrapper = GuesserWrapper(guesser_network)
        qgen_network.build_sampling_graph(qgen_config["model"], tokenizer=tokenizer, max_length=loop_config['loop']['max_depth'])
        qgen_wrapper = QGenWrapper(qgen_network, tokenizer,
                                   max_length=loop_config['loop']['max_depth'],
                                   k_best=loop_config['loop']['beam_k_best'])

        looper_evaluator = BasicLooper(loop_config,
                                       oracle_wrapper=oracle_wrapper,
                                       guesser_wrapper=guesser_wrapper,
                                       qgen_wrapper=qgen_wrapper,
                                       tokenizer=tokenizer,
                                       batch_size=loop_config["optimizer"]["batch_size"])

        # Compute the initial scores
        logger.info(">>>-------------- INITIAL SCORE ---------------------<<<")

        logger.info(">>>  Initial models  <<<")
        test_model(sess, testset, cpu_pool=cpu_pool, tokenizer=tokenizer,
                   oracle=oracle_network,guesser=guesser_network, qgen=qgen_network,
                   batch_size=batch_size*2, logger=logger)

        logger.info(">>>  New Objects  <<<")
        compute_qgen_accuracy(sess, trainset, batchifier=train_batchifier, evaluator=looper_evaluator, tokenizer=tokenizer,
                              mode=mode_to_evaluate, save_path=save_path, cpu_pool=cpu_pool, batch_size=batch_size,
                              store_games=args.store_games, dump_suffix="init.new_object")

        logger.info(">>>  New Games  <<<")
        compute_qgen_accuracy(sess, testset, batchifier=eval_batchifier, evaluator=looper_evaluator, tokenizer=tokenizer,
                              mode=mode_to_evaluate, save_path=save_path, cpu_pool=cpu_pool, batch_size=batch_size,
                              store_games=args.store_games, dump_suffix="init.new_games")
        logger.info(">>>------------------------------------------------<<<")

        if args.skip_training:
            logger.info("Skip training...")
            exit(0)

        logs = []
        # Start training
        final_val_score = 0.
        for epoch in range(no_epoch):

            logger.info("Epoch {}/{}".format(epoch, no_epoch))

            train_iterator = Iterator(trainset, batch_size=batch_size,
                                      pool=cpu_pool,
                                      batchifier=train_batchifier,
                                      use_padding=True)
            train_score = looper_evaluator.process(sess, train_iterator,
                                                   optimizer=optimizer,
                                                   mode="sampling")

            valid_iterator = Iterator(validset, pool=cpu_pool,
                                      batch_size=batch_size,
                                      batchifier=eval_batchifier,
                                      shuffle=False,
                                      use_padding=True)
            val_score = looper_evaluator.process(sess, valid_iterator, mode="sampling")

            logger.info("Accuracy (train - sampling) : {}".format(train_score))
            logger.info("Accuracy (valid - sampling) : {}".format(val_score))

            if val_score > final_val_score:
                logger.info("Save checkpoint...")
                final_val_score = val_score
                loop_saver.save(sess, save_path.format('params.ckpt'))

        # Compute the test score with early stopping
        logger.info(">>>-------------- FINAL SCORE ---------------------<<<")
        loop_saver.restore(sess, save_path.format('params.ckpt'))

        logger.info(">>>  New Objects  <<<")
        compute_qgen_accuracy(sess, trainset, batchifier=train_batchifier, evaluator=looper_evaluator, tokenizer=tokenizer,
                              mode=mode_to_evaluate, save_path=save_path, cpu_pool=cpu_pool, batch_size=batch_size,
                              store_games=args.store_games, dump_suffix="final.new_object")

        logger.info(">>>  New Games  <<<")
        compute_qgen_accuracy(sess, testset, batchifier=eval_batchifier, evaluator=looper_evaluator, tokenizer=tokenizer,
                              mode=mode_to_evaluate, save_path=save_path, cpu_pool=cpu_pool, batch_size=batch_size,
                              store_games=args.store_games, dump_suffix="final.new_games")
        logger.info(">>>------------------------------------------------<<<")


text:
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin Core developers
// Copyright (c) 2017 The FxBitLab Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "chainparams.h"
#include "consensus/merkle.h"

#include "tinyformat.h"
#include "util.h"
#include "utilstrencodings.h"

#include <assert.h>

#include <boost/assign/list_of.hpp>

#include "chainparamsseeds.h"
#include <stdio.h>

static CBlock CreateGenesisBlock(const char* pszTimestamp, const CScript& genesisOutputScript, uint32_t nTime, uint32_t nNonce, uint32_t nBits, int32_t nVersion, const CAmount& genesisReward)
{
    CMutableTransaction txNew;
    txNew.nVersion = 1;
    txNew.vin.resize(1);
    txNew.vout.resize(1);
    txNew.vin[0].scriptSig = CScript() << 486604799 << CScriptNum(4) << std::vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
    txNew.vout[0].nValue = genesisReward;
    txNew.vout[0].scriptPubKey = genesisOutputScript;

    CBlock genesis;
    genesis.nTime    = nTime;
    genesis.nBits    = nBits;
    genesis.nNonce   = nNonce;
    genesis.nVersion = nVersion;
    genesis.vtx.push_back(txNew);
    genesis.hashPrevBlock.SetNull();
    genesis.hashMerkleRoot = BlockMerkleRoot(genesis);
    return genesis;
}

/**
 * Build the genesis block. Note that the output of its generation
 * transaction cannot be spent since it did not originally exist in the
 * database.
 *
 * CBlock(hash=00000ffd590b14, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=e0028e, nTime=1390095618, nBits=1e0ffff0, nNonce=28917698, vtx=1)
 *   CTransaction(hash=e0028e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
 *     CTxIn(COutPoint(000000, -1), coinbase 04ffff001d01044c5957697265642030392f4a616e2f3230313420546865204772616e64204578706572696d656e7420476f6573204c6976653a204f76657273746f636b2e636f6d204973204e6f7720416363657074696e6720426974636f696e73)
 *     CTxOut(nValue=50.00000000, scriptPubKey=0xA9037BAC7050C479B121CF)
 *   vMerkleTree: e0028e
 */
static CBlock CreateGenesisBlock(uint32_t nTime, uint32_t nNonce, uint32_t nBits, int32_t nVersion, const CAmount& genesisReward)
{
    const char* pszTimestamp = "Wired 29/Augt/2017 Aya, finally you successfully forking Dash coin";
    const CScript genesisOutputScript = CScript() << ParseHex("04d9bc30a8e9816a6af525f00f4f0b70da9b0faaee6334a2fcc0b16b9c5d5256efd143db3071e29cfeb891aa2420c124167c60ea482fa09dfa7ec4c15d7944ff60") << OP_CHECKSIG;
    return CreateGenesisBlock(pszTimestamp, genesisOutputScript, nTime, nNonce, nBits, nVersion, genesisReward);
}

/**
 * Main network
 */
/**
 * What makes a good checkpoint block?
 * + Is surrounded by blocks with reasonable timestamps
 *   (no blocks before with a timestamp after, none after with
 *    timestamp before)
 * + Contains no strange transactions
 */

class CMainParams : public CChainParams {
public:
    CMainParams() {
        strNetworkID = "main";
        consensus.nSubsidyHalvingInterval = 210240; // Note: actual number of blocks per calendar year with DGW v3 is ~200700 (for example 449750 - 249050)
        consensus.nMasternodePaymentsStartBlock = 100000; // not true, but it's ok as long as it's less then nMasternodePaymentsIncreaseBlock
        consensus.nMasternodePaymentsIncreaseBlock = 158000; // actual historical value
        consensus.nMasternodePaymentsIncreasePeriod = 576*30; // 17280 - actual historical value
        consensus.nInstantSendKeepLock = 24;
        consensus.nBudgetPaymentsStartBlock = 328008; // actual historical value
        consensus.nBudgetPaymentsCycleBlocks = 16616; // ~(60*24*30)/2.6, actual number of blocks per month is 200700 / 12 = 16725
        consensus.nBudgetPaymentsWindowBlocks = 100;
        consensus.nBudgetProposalEstablishingTime = 60*60*24;
        consensus.nSuperblockStartBlock = 614820; // The block at which 12.1 goes live (end of final 12.0 budget cycle)
        consensus.nSuperblockCycle = 16616; // ~(60*24*30)/2.6, actual number of blocks per month is 200700 / 12 = 16725
        consensus.nGovernanceMinQuorum = 10;
        consensus.nGovernanceFilterElements = 20000;
        consensus.nMasternodeMinimumConfirmations = 15;
        consensus.nMajorityEnforceBlockUpgrade = 750;
        consensus.nMajorityRejectBlockOutdated = 950;
        consensus.nMajorityWindow = 1000;
        consensus.BIP34Height = 227931;
        consensus.BIP34Hash = uint256S("0x000000000000024b89b42a942fe0d9fea3bb44ab7bd1b19115dd6a759c0808b8");
        consensus.powLimit = uint256S("00000fffff000000000000000000000000000000000000000000000000000000");
        consensus.nPowTargetTimespan = 24 * 60 * 60; // Etp: 1 day
        consensus.nPowTargetSpacing = 2.5 * 60; // Etp: 2.5 minutes
        consensus.fPowAllowMinDifficultyBlocks = false;
        consensus.fPowNoRetargeting = false;
        consensus.nRuleChangeActivationThreshold = 1916; // 95% of 2016
        consensus.nMinerConfirmationWindow = 2016; // nPowTargetTimespan / nPowTargetSpacing
        consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28;
        consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 1199145601; // January 1, 2008
        consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 1230767999; // December 31, 2008

        // Deployment of BIP68, BIP112, and BIP113.
        consensus.vDeployments[Consensus::DEPLOYMENT_CSV].bit = 0;
        consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 1486252800; // Feb 5th, 2017
        consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = 1517788800; // Feb 5th, 2018

        /**
         * The message start string is designed to be unlikely to occur in normal data.
         * The characters are rarely used upper ASCII, not valid as UTF-8, and produce
         * a large 32-bit integer with any alignment.
         */
        pchMessageStart[0] = 0xbf;
        pchMessageStart[1] = 0x0c;
        pchMessageStart[2] = 0x6b;
        pchMessageStart[3] = 0xbd;
        vAlertPubKey = ParseHex("04486efc67bf403e991f2c4bdd9a68036afd230da009748bb2d06f2cd63d52dcf2b2d2ad5c707a77462649aaf0db652acbe53de6995c28fec112d1e04ba4c84582");
        nDefaultPort = 7899;
        nMaxTipAge = 6 * 60 * 60; // ~144 blocks behind -> 2 x fork detection time, was 24 * 60 * 60 in bitcoin
        nPruneAfterHeight = 100000;

        genesis = CreateGenesisBlock(1503994587, 1463218, 0x1e0ffff0, 1, 50 * COIN);
        consensus.hashGenesisBlock = genesis.GetHash();
	//consensus.hashGenesisBlock = uint256S("0x01");
	/*if (true && genesis.GetHash() != consensus.hashGenesisBlock)
        {
            printf("recalculating params for mainnet.\n");
            printf("old mainnet genesis nonce: %u\n", genesis.nNonce);
            printf("old mainnet genesis hash:  %s\n", consensus.hashGenesisBlock.ToString().c_str());
            // deliberately empty for loop finds nonce value.

            for(genesis.nNonce = 0; genesis.GetHash().ToString() > consensus.powLimit.ToString(); genesis.nNonce++){
		printf("nonce : %u\n", genesis.nNonce);
	    }
            printf("new mainnet genesis merkle root: %s\n", genesis.hashMerkleRoot.ToString().c_str());
            printf("new mainnet genesis nonce: %u\n", genesis.nNonce);
            printf("new mainnet genesis hash: %s\n", genesis.GetHash().ToString().c_str());
        }
	*/

        assert(consensus.hashGenesisBlock == uint256S("0x000009df8f3ee928703c23d19508becd3f8d8195f60fbf1c1bcf8eee6a31d9d8"));
        assert(genesis.hashMerkleRoot == uint256S("0xa2bbebba735bfbbfe829706db834d23a058d23818741671a271d19269ba55e58"));

	/*
        vSeeds.push_back(CDNSSeedData("dash.org", "dnsseed.dash.org"));
        vSeeds.push_back(CDNSSeedData("dashdot.io", "dnsseed.dashdot.io"));
        vSeeds.push_back(CDNSSeedData("masternode.io", "dnsseed.masternode.io"));
        vSeeds.push_back(CDNSSeedData("dashpay.io", "dnsseed.dashpay.io"));
	*/
	vFixedSeeds.clear(); //We dont have any dns seed yet
        vSeeds.clear();  //! We doesn't have any DNS seeds.

	pchMessageStart[0] = 0xdb;
        pchMessageStart[1] = 0xab;
        pchMessageStart[2] = 0x66;
        pchMessageStart[3] = 0x0a;
        // Etp addresses start with 'X'
        base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,76);
        // Etp script addresses start with '7'
        base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,16);
        // Etp private keys start with '7' or 'X'
        base58Prefixes[SECRET_KEY] =     std::vector<unsigned char>(1,204);
        // Etp BIP32 pubkeys start with 'xpub' (Bitcoin defaults)
        base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x88)(0xB2)(0x1E).convert_to_container<std::vector<unsigned char> >();
        // Etp BIP32 prvkeys start with 'xprv' (Bitcoin defaults)
        base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x88)(0xAD)(0xE4).convert_to_container<std::vector<unsigned char> >();
        // Etp BIP44 coin type is '5'
        base58Prefixes[EXT_COIN_TYPE]  = boost::assign::list_of(0x80)(0x00)(0x00)(0x05).convert_to_container<std::vector<unsigned char> >();

        vFixedSeeds = std::vector<SeedSpec6>(pnSeed6_main, pnSeed6_main + ARRAYLEN(pnSeed6_main));

        fMiningRequiresPeers = true;
        fDefaultConsistencyChecks = false;
        fRequireStandard = true;
        fMineBlocksOnDemand = false;
        fTestnetToBeDeprecatedFieldRPC = false;

        nPoolMaxTransactions = 3;
        nFulfilledRequestExpireTime = 60*60; // fulfilled requests expire in 1 hour
        strSporkPubKey = "04549ac134f694c0243f503e8c8a9a986f5de6610049c40b07816809b0d1d06a21b07be27b9bb555931773f62ba6cf35a25fd52f694d4e1106ccd237a7bb899fdd";
        strMasternodePaymentsPubKey = "04549ac134f694c0243f503e8c8a9a986f5de6610049c40b07816809b0d1d06a21b07be27b9bb555931773f62ba6cf35a25fd52f694d4e1106ccd237a7bb899fdd";

        checkpointData = (CCheckpointData) {
            boost::assign::map_list_of
            (  1500, uint256S("0x000000aaf0300f59f49bc3e970bad15c11f961fe2347accffff19d96ec9778e3"))
            (  4991, uint256S("0x000000003b01809551952460744d5dbb8fcbd6cbae3c220267bf7fa43f837367"))
            (  9918, uint256S("0x00000000213e229f332c0ffbe34defdaa9e74de87f2d8d1f01af8d121c3c170b"))
            ( 16912, uint256S("0x00000000075c0d10371d55a60634da70f197548dbbfa4123e12abfcbc5738af9"))
            ( 23912, uint256S("0x0000000000335eac6703f3b1732ec8b2f89c3ba3a7889e5767b090556bb9a276"))
            ( 35457, uint256S("0x0000000000b0ae211be59b048df14820475ad0dd53b9ff83b010f71a77342d9f"))
            ( 45479, uint256S("0x000000000063d411655d590590e16960f15ceea4257122ac430c6fbe39fbf02d"))
            ( 55895, uint256S("0x0000000000ae4c53a43639a4ca027282f69da9c67ba951768a20415b6439a2d7"))
            ( 68899, uint256S("0x0000000000194ab4d3d9eeb1f2f792f21bb39ff767cb547fe977640f969d77b7"))
            ( 74619, uint256S("0x000000000011d28f38f05d01650a502cc3f4d0e793fbc26e2a2ca71f07dc3842"))
            ( 75095, uint256S("0x0000000000193d12f6ad352a9996ee58ef8bdc4946818a5fec5ce99c11b87f0d"))
            ( 88805, uint256S("0x00000000001392f1652e9bf45cd8bc79dc60fe935277cd11538565b4a94fa85f"))
            ( 107996, uint256S("0x00000000000a23840ac16115407488267aa3da2b9bc843e301185b7d17e4dc40"))
            ( 137993, uint256S("0x00000000000cf69ce152b1bffdeddc59188d7a80879210d6e5c9503011929c3c"))
            ( 167996, uint256S("0x000000000009486020a80f7f2cc065342b0c2fb59af5e090cd813dba68ab0fed"))
            ( 207992, uint256S("0x00000000000d85c22be098f74576ef00b7aa00c05777e966aff68a270f1e01a5"))
            ( 312645, uint256S("0x0000000000059dcb71ad35a9e40526c44e7aae6c99169a9e7017b7d84b1c2daf"))
            ( 407452, uint256S("0x000000000003c6a87e73623b9d70af7cd908ae22fee466063e4ffc20be1d2dbc"))
            ( 523412, uint256S("0x000000000000e54f036576a10597e0e42cc22a5159ce572f999c33975e121d4d"))
            ( 523930, uint256S("0x0000000000000bccdb11c2b1cfb0ecab452abf267d89b7f46eaf2d54ce6e652c")),
            1471809614, // * UNIX timestamp of last checkpoint block
            1998064,    // * total number of transactions between genesis and last checkpoint
                        //   (the tx=... number in the SetBestChain debug.log lines)
            2800        // * estimated number of transactions per day after checkpoint
        };
    }
};
static CMainParams mainParams;

/**
 * Testnet (v3)
 */
class CTestNetParams : public CChainParams {
public:
    CTestNetParams() {
        strNetworkID = "test";
        consensus.nSubsidyHalvingInterval = 210240;
        consensus.nMasternodePaymentsStartBlock = 10000; // not true, but it's ok as long as it's less then nMasternodePaymentsIncreaseBlock
        consensus.nMasternodePaymentsIncreaseBlock = 46000;
        consensus.nMasternodePaymentsIncreasePeriod = 576;
        consensus.nInstantSendKeepLock = 6;
        consensus.nBudgetPaymentsStartBlock = 60000;
        consensus.nBudgetPaymentsCycleBlocks = 50;
        consensus.nBudgetPaymentsWindowBlocks = 10;
        consensus.nBudgetProposalEstablishingTime = 60*20;
        consensus.nSuperblockStartBlock = 61000; // NOTE: Should satisfy nSuperblockStartBlock > nBudgetPeymentsStartBlock
        consensus.nSuperblockCycle = 24; // Superblocks can be issued hourly on testnet
        consensus.nGovernanceMinQuorum = 1;
        consensus.nGovernanceFilterElements = 500;
        consensus.nMasternodeMinimumConfirmations = 1;
        consensus.nMajorityEnforceBlockUpgrade = 51;
        consensus.nMajorityRejectBlockOutdated = 75;
        consensus.nMajorityWindow = 100;
        consensus.BIP34Height = 21111;
        consensus.BIP34Hash = uint256S("0x0000000023b3a96d3484e5abb3755c413e7d41500f8e2a5c3f0dd01299cd8ef8");
        consensus.powLimit = uint256S("00000fffff000000000000000000000000000000000000000000000000000000");
        consensus.nPowTargetTimespan = 24 * 60 * 60; // Etp: 1 day
        consensus.nPowTargetSpacing = 2.5 * 60; // Etp: 2.5 minutes
        consensus.fPowAllowMinDifficultyBlocks = true;
        consensus.fPowNoRetargeting = false;
        consensus.nRuleChangeActivationThreshold = 1512; // 75% for testchains
        consensus.nMinerConfirmationWindow = 2016; // nPowTargetTimespan / nPowTargetSpacing
        consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28;
        consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 1199145601; // January 1, 2008
        consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 1230767999; // December 31, 2008

        // Deployment of BIP68, BIP112, and BIP113.
        consensus.vDeployments[Consensus::DEPLOYMENT_CSV].bit = 0;
        consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 1456790400; // March 1st, 2016
        consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = 1493596800; // May 1st, 2017

        /*pchMessageStart[0] = 0xce;
        pchMessageStart[1] = 0xe2;
        pchMessageStart[2] = 0xca;
        pchMessageStart[3] = 0xff;
	*/
	pchMessageStart[0] = 0x58;
        pchMessageStart[1] = 0xde;
        pchMessageStart[2] = 0x40;
        pchMessageStart[3] = 0xc7;

        vAlertPubKey = ParseHex("04023b2f70f3ac9904c3674f0f22e578762b4b26229c24f5c1c2f8e3849f040be6b7c10870242711bec3b60f0bb67b64ee6c0bfac00bc74bce618c735570342a3e");
        nDefaultPort = 17899;
        nMaxTipAge = 0x7fffffff; // allow mining on top of old blocks for testnet
        nPruneAfterHeight = 1000;

        genesis = CreateGenesisBlock(1504001834, 263533, 0x1e0ffff0, 1, 50 * COIN);
        consensus.hashGenesisBlock = genesis.GetHash();
	/*consensus.hashGenesisBlock = uint256S("0x01");
        if (true && genesis.GetHash() != consensus.hashGenesisBlock)
        {
            printf("recalculating params for testnet.\n");
            printf("old testnet genesis nonce: %u\n", genesis.nNonce);
            printf("old testnet genesis hash:  %s\n", consensus.hashGenesisBlock.ToString().c_str());
            // deliberately empty for loop finds nonce value.

            for(genesis.nNonce = 0; genesis.GetHash().ToString() > consensus.powLimit.ToString(); genesis.nNonce++){
                printf("nonce : %u\n", genesis.nNonce);
            }
            printf("new testnet genesis merkle root: %s\n", genesis.hashMerkleRoot.ToString().c_str());
            printf("new testnet genesis nonce: %u\n", genesis.nNonce);
            printf("new testnet genesis hash: %s\n", genesis.GetHash().ToString().c_str());
        }
	*/
        assert(consensus.hashGenesisBlock == uint256S("0x0000074e8d62de210a7d6394c7500cb97d45afc82c5fb061aab6b81d494583ed"));
        assert(genesis.hashMerkleRoot == uint256S("0xa2bbebba735bfbbfe829706db834d23a058d23818741671a271d19269ba55e58"));

        vFixedSeeds.clear();
        vSeeds.clear();
        //vSeeds.push_back(CDNSSeedData("dashdot.io",  "testnet-seed.dashdot.io"));
        //vSeeds.push_back(CDNSSeedData("masternode.io", "test.dnsseed.masternode.io"));

        // Testnet Etp addresses start with 'y'
        base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,140);
        // Testnet Etp script addresses start with '8' or '9'
        base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,19);
        // Testnet private keys start with '9' or 'c' (Bitcoin defaults)
        base58Prefixes[SECRET_KEY] =     std::vector<unsigned char>(1,239);
        // Testnet Etp BIP32 pubkeys start with 'tpub' (Bitcoin defaults)
        base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x35)(0x87)(0xCF).convert_to_container<std::vector<unsigned char> >();
        // Testnet Etp BIP32 prvkeys start with 'tprv' (Bitcoin defaults)
        base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x35)(0x83)(0x94).convert_to_container<std::vector<unsigned char> >();
        // Testnet Etp BIP44 coin type is '1' (All coin's testnet default)
        base58Prefixes[EXT_COIN_TYPE]  = boost::assign::list_of(0x80)(0x00)(0x00)(0x01).convert_to_container<std::vector<unsigned char> >();

        vFixedSeeds = std::vector<SeedSpec6>(pnSeed6_test, pnSeed6_test + ARRAYLEN(pnSeed6_test));

        fMiningRequiresPeers = true;
        fDefaultConsistencyChecks = false;
        fRequireStandard = false;
        fMineBlocksOnDemand = false;
        fTestnetToBeDeprecatedFieldRPC = true;

        nPoolMaxTransactions = 3;
        nFulfilledRequestExpireTime = 5*60; // fulfilled requests expire in 5 minutes
        strSporkPubKey = "046f78dcf911fbd61910136f7f0f8d90578f68d0b3ac973b5040fb7afb501b5939f39b108b0569dca71488f5bbf498d92e4d1194f6f941307ffd95f75e76869f0e";
        strMasternodePaymentsPubKey = "046f78dcf911fbd61910136f7f0f8d90578f68d0b3ac973b5040fb7afb501b5939f39b108b0569dca71488f5bbf498d92e4d1194f6f941307ffd95f75e76869f0e";

        checkpointData = (CCheckpointData) {
            boost::assign::map_list_of
            (    261, uint256S("0x00000c26026d0815a7e2ce4fa270775f61403c040647ff2c3091f99e894a4618"))
            (   1999, uint256S("0x00000052e538d27fa53693efe6fb6892a0c1d26c0235f599171c48a3cce553b1"))
            (   2999, uint256S("0x0000024bc3f4f4cb30d29827c13d921ad77d2c6072e586c7f60d83c2722cdcc5"))
            (  12907, uint256S("0x00000067de20fd6d276ee0839a3187b203accaa5aad04ca5c17c2997e2730e4c"))
            (  15590, uint256S("0x00000009df8f2ee9c230aef9dad257d82bde20ca83378a208ce5d95d29a78852"))
            (  65900, uint256S("0x00000063e4e94d75d0dc075e93898444c8ef50655990dfff7c32d92a7efff671"))
            ( 127618, uint256S("0x0000002104a2c1fc923b0e3b74b1860236fbc2b4479a833c28abaf456ea4e466")),

            1483076495, // * UNIX timestamp of last checkpoint block
            168590,     // * total number of transactions between genesis and last checkpoint
                        //   (the tx=... number in the SetBestChain debug.log lines)
            500         // * estimated number of transactions per day after checkpoint
        };

    }
};
static CTestNetParams testNetParams;

/**
 * Regression test
 */
class CRegTestParams : public CChainParams {
public:
    CRegTestParams() {
        strNetworkID = "regtest";
        consensus.nSubsidyHalvingInterval = 150;
        consensus.nMasternodePaymentsStartBlock = 240;
        consensus.nMasternodePaymentsIncreaseBlock = 350;
        consensus.nMasternodePaymentsIncreasePeriod = 10;
        consensus.nInstantSendKeepLock = 6;
        consensus.nBudgetPaymentsStartBlock = 1000;
        consensus.nBudgetPaymentsCycleBlocks = 50;
        consensus.nBudgetPaymentsWindowBlocks = 10;
        consensus.nBudgetProposalEstablishingTime = 60*20;
        consensus.nSuperblockStartBlock = 1500;
        consensus.nSuperblockCycle = 10;
        consensus.nGovernanceMinQuorum = 1;
        consensus.nGovernanceFilterElements = 100;
        consensus.nMasternodeMinimumConfirmations = 1;
        consensus.nMajorityEnforceBlockUpgrade = 750;
        consensus.nMajorityRejectBlockOutdated = 950;
        consensus.nMajorityWindow = 1000;
        consensus.BIP34Height = -1; // BIP34 has not necessarily activated on regtest
        consensus.BIP34Hash = uint256();
        consensus.powLimit = uint256S("00000fffff000000000000000000000000000000000000000000000000000000");
        consensus.nPowTargetTimespan = 24 * 60 * 60; // Etp: 1 day
        consensus.nPowTargetSpacing = 2.5 * 60; // Etp: 2.5 minutes
        consensus.fPowAllowMinDifficultyBlocks = true;
        consensus.fPowNoRetargeting = true;
        consensus.nRuleChangeActivationThreshold = 108; // 75% for testchains
        consensus.nMinerConfirmationWindow = 144; // Faster than normal for regtest (144 instead of 2016)
        consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28;
        consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 0;
        consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 999999999999ULL;
        consensus.vDeployments[Consensus::DEPLOYMENT_CSV].bit = 0;
        consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 0;
        consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = 999999999999ULL;

        pchMessageStart[0] = 0xfc;
        pchMessageStart[1] = 0xc1;
        pchMessageStart[2] = 0xb7;
        pchMessageStart[3] = 0xdc;
        nMaxTipAge = 6 * 60 * 60; // ~144 blocks behind -> 2 x fork detection time, was 24 * 60 * 60 in bitcoin
        nDefaultPort = 17894;
        nPruneAfterHeight = 1000;

        genesis = CreateGenesisBlock(1504005687, 197115, 0x207fffff, 1, 50 * COIN);
        consensus.hashGenesisBlock = genesis.GetHash();

	/*consensus.hashGenesisBlock = uint256S("0x01");
        if (true && genesis.GetHash() != consensus.hashGenesisBlock)
        {
            printf("recalculating params for regtestnet.\n");
            printf("old regtestnet genesis nonce: %u\n", genesis.nNonce);
            printf("old regtestnet genesis hash:  %s\n", consensus.hashGenesisBlock.ToString().c_str());
            // deliberately empty for loop finds nonce value.
	    printf("genesis.GetHash().ToString() : %s\n", genesis.GetHash().ToString().c_str());
	    printf("consensus.powLimit.ToString(): %s\n", consensus.powLimit.ToString().c_str());
            for(genesis.nNonce = 0; genesis.GetHash().ToString() > consensus.powLimit.ToString(); genesis.nNonce++){
                printf("nonce : %u\n", genesis.nNonce);
            }
            printf("new regtestnet genesis merkle root: %s\n", genesis.hashMerkleRoot.ToString().c_str());
            printf("new regtestnet genesis nonce: %u\n", genesis.nNonce);
            printf("new regtestnet genesis hash: %s\n", genesis.GetHash().ToString().c_str());
        } */

        assert(consensus.hashGenesisBlock == uint256S("0x00000e6ef6bde7d2a06cdd68eb01e7b525a038630a31963419113297820eb60e"));
        assert(genesis.hashMerkleRoot == uint256S("0xa2bbebba735bfbbfe829706db834d23a058d23818741671a271d19269ba55e58"));

        vFixedSeeds.clear(); //! Regtest mode doesn't have any fixed seeds.
        vSeeds.clear();  //! Regtest mode doesn't have any DNS seeds.

        fMiningRequiresPeers = false;
        fDefaultConsistencyChecks = true;
        fRequireStandard = false;
        fMineBlocksOnDemand = true;
        fTestnetToBeDeprecatedFieldRPC = false;

        nFulfilledRequestExpireTime = 5*60; // fulfilled requests expire in 5 minutes

        checkpointData = (CCheckpointData){
            boost::assign::map_list_of
            ( 0, uint256S("0x000008ca1832a4baf228eb1553c03d3a2c8e02399550dd6ea8d65cec3ef23d2e")),
            0,
            0,
            0
        };
        // Regtest Etp addresses start with 'y'
        base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,140);
        // Regtest Etp script addresses start with '8' or '9'
        base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,19);
        // Regtest private keys start with '9' or 'c' (Bitcoin defaults)
        base58Prefixes[SECRET_KEY] =     std::vector<unsigned char>(1,239);
        // Regtest Etp BIP32 pubkeys start with 'tpub' (Bitcoin defaults)
        base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x35)(0x87)(0xCF).convert_to_container<std::vector<unsigned char> >();
        // Regtest Etp BIP32 prvkeys start with 'tprv' (Bitcoin defaults)
        base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x35)(0x83)(0x94).convert_to_container<std::vector<unsigned char> >();
        // Regtest Etp BIP44 coin type is '1' (All coin's testnet default)
        base58Prefixes[EXT_COIN_TYPE]  = boost::assign::list_of(0x80)(0x00)(0x00)(0x01).convert_to_container<std::vector<unsigned char> >();
   }
};
static CRegTestParams regTestParams;

static CChainParams *pCurrentParams = 0;

const CChainParams &Params() {
    assert(pCurrentParams);
    return *pCurrentParams;
}

CChainParams& Params(const std::string& chain)
{
    if (chain == CBaseChainParams::MAIN)
            return mainParams;
    else if (chain == CBaseChainParams::TESTNET)
            return testNetParams;
    else if (chain == CBaseChainParams::REGTEST)
            return regTestParams;
    else
        throw std::runtime_error(strprintf("%s: Unknown chain %s.", __func__, chain));
}

void SelectParams(const std::string& network)
{
    SelectBaseParams(network);
    pCurrentParams = &Params(network);
}

redpajama_set_name: RedPajamaGithub


text:
#include <stdint.h>
#include <sys/types.h>

#include <binder/IInterface.h>
#include <binder/Parcel.h>

#include <gui/IConsumerListener.h>

// ---------------------------------------------------------------------------
namespace android {
// ---------------------------------------------------------------------------

enum {
    ON_FRAME_AVAILABLE = IBinder::FIRST_CALL_TRANSACTION,
    ON_BUFFER_RELEASED
};

class BpConsumerListener : public BpInterface<IConsumerListener>
{
public:
    BpConsumerListener(const sp<IBinder>& impl)
        : BpInterface<IConsumerListener>(impl) {
    }

    virtual void onFrameAvailable() {
        Parcel data, reply;
        data.writeInterfaceToken(IConsumerListener::getInterfaceDescriptor());
        remote()->transact(ON_FRAME_AVAILABLE, data, &reply, IBinder::FLAG_ONEWAY);
    }

    virtual void onBuffersReleased() {
        Parcel data, reply;
        data.writeInterfaceToken(IConsumerListener::getInterfaceDescriptor());
        remote()->transact(ON_BUFFER_RELEASED, data, &reply, IBinder::FLAG_ONEWAY);
    }
};

IMPLEMENT_META_INTERFACE(ConsumerListener, "android.gui.IConsumerListener");

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

status_t BnConsumerListener::onTransact(
    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
{
    switch(code) {
        case ON_FRAME_AVAILABLE:
            CHECK_INTERFACE(IConsumerListener, data, reply);
            onFrameAvailable();
            return NO_ERROR;
        case ON_BUFFER_RELEASED:
            CHECK_INTERFACE(IConsumerListener, data, reply);
            onBuffersReleased();
            return NO_ERROR;
    }
    return BBinder::onTransact(code, data, reply, flags);
}

// ---------------------------------------------------------------------------
}; // namespace android
// ---------------------------------------------------------------------------


text:
from __future__ import print_function
import os
from setuptools import setup
import codecs

def read(fname):
    with codecs.open(fname, 'r', 'latin') as f:
        return f.read()

def read_to_rst(fname):
    try:
        import pypandoc
        rstname = "{}.{}".format(os.path.splitext(fname)[0], 'rst')
        pypandoc.convert(read(fname), 'rst', format='md', outputfile=rstname)
        with open(rstname, 'r') as f:
            rststr = f.read()
        return rststr
        #return read(rstname)
    except ImportError:
        return read(fname)

desc = read_to_rst('README.md')

version_dummy = {}
exec(read('paramz/__version__.py'), version_dummy)
__version__ = version_dummy['__version__']
del version_dummy

#Mac OS X Clang doesn't support OpenMP at the current time.
#This detects if we are building on a Mac
# def ismac():
#     return sys.platform[:6] == 'darwin'
#
# if ismac():
#     compile_flags = [ '-O3', ]
#     link_args = []
# else:
#     compile_flags = [ '-fopenmp', '-O3', ]
#     link_args = ['-lgomp']

# ext_mods = [Extension(name='GPy.kern._src.stationary_cython',
#                       sources=['GPy/kern/_src/stationary_cython.c',
#                                'GPy/kern/_src/stationary_utils.c'],
#                       include_dirs=[np.get_include(),'.'],
#                       extra_compile_args=compile_flags,
#                       extra_link_args = link_args),
#             Extension(name='GPy.util.choleskies_cython',
#                       sources=['GPy/util/choleskies_cython.c'],
#                       include_dirs=[np.get_include(),'.'],
#                       extra_link_args = link_args,
#                       extra_compile_args=compile_flags),
#             Extension(name='GPy.util.linalg_cython',
#                       sources=['GPy/util/linalg_cython.c'],
#                       include_dirs=[np.get_include(),'.'],
#                       extra_compile_args=compile_flags),
#             Extension(name='GPy.kern._src.coregionalize_cython',
#                       sources=['GPy/kern/_src/coregionalize_cython.c'],
#                       include_dirs=[np.get_include(),'.'],
#                       extra_compile_args=compile_flags)]

setup(name = 'paramz',
      version = __version__,
      author = 'Max Zwiessele',
      author_email = "ibinbei@gmail.com",
      description = ("The Parameterization Framework"),
      license = "BSD 3-clause",
      keywords = "machine-learning gaussian-processes kernels",
      url = "https://github.com/mzwiessele/paramz",
      #ext_modules = ext_mods,
      packages = ["paramz",
                  "paramz.core",
                  "paramz.optimization",
                  "paramz.examples",
                  "paramz.tests"
                  ],
      #package_dir={'GPy': 'GPy'},
      #package_data = {'GPy': ['defaults.cfg', 'installation.cfg',
      #                        'util/data_resources.json',
      #                        'util/football_teams.json',
      #                        ]},
      #include_package_data = True,
      py_modules = ['paramz.__init__'],
      test_suite = 'paramz.tests',
      long_description=desc,
      install_requires=['numpy>=1.7', 'scipy', 'six', 'decorator'],
      extras_require = {'docs':['sphinx'],
                        'notebook':['jupyter_client >= 4.0.6',
                                    'ipywidgets >= 4.0.3',
                                    'ipykernel >= 4.1.0',
                                    'notebook >= 4.0.5',
                                    ],
                        'optimization':['climin'],
                        },
      classifiers=['License :: OSI Approved :: BSD License',
                   'Natural Language :: English',
                   'Operating System :: MacOS :: MacOS X',
                   'Operating System :: Microsoft :: Windows',
                   'Operating System :: POSIX :: Linux',
                   'Programming Language :: Python :: 2.7',
                   'Programming Language :: Python :: 3.3',
                   'Programming Language :: Python :: 3.4',
                   'Programming Language :: Python :: 3.5',
                   'Topic :: Scientific/Engineering :: Artificial Intelligence']
      )


text:
"""SCons.Tool.ifl

Tool-specific initialization for the Intel Fortran compiler.

There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.

"""

#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#

__revision__ = "src/engine/SCons/Tool/ifl.py 5357 2011/09/09 21:31:03 bdeegan"

import SCons.Defaults
from SCons.Scanner.Fortran import FortranScan
from FortranCommon import add_all_to_env

def generate(env):
    """Add Builders and construction variables for ifl to an Environment."""
    fscan = FortranScan("FORTRANPATH")
    SCons.Tool.SourceFileScanner.add_scanner('.i', fscan)
    SCons.Tool.SourceFileScanner.add_scanner('.i90', fscan)

    if 'FORTRANFILESUFFIXES' not in env:
        env['FORTRANFILESUFFIXES'] = ['.i']
    else:
        env['FORTRANFILESUFFIXES'].append('.i')

    if 'F90FILESUFFIXES' not in env:
        env['F90FILESUFFIXES'] = ['.i90']
    else:
        env['F90FILESUFFIXES'].append('.i90')

    add_all_to_env(env)

    env['FORTRAN']        = 'ifl'
    env['SHFORTRAN']      = '$FORTRAN'
    env['FORTRANCOM']     = '$FORTRAN $FORTRANFLAGS $_FORTRANINCFLAGS /c $SOURCES /Fo$TARGET'
    env['FORTRANPPCOM']   = '$FORTRAN $FORTRANFLAGS $CPPFLAGS $_CPPDEFFLAGS $_FORTRANINCFLAGS /c $SOURCES /Fo$TARGET'
    env['SHFORTRANCOM']   = '$SHFORTRAN $SHFORTRANFLAGS $_FORTRANINCFLAGS /c $SOURCES /Fo$TARGET'
    env['SHFORTRANPPCOM'] = '$SHFORTRAN $SHFORTRANFLAGS $CPPFLAGS $_CPPDEFFLAGS $_FORTRANINCFLAGS /c $SOURCES /Fo$TARGET'

def exists(env):
    return env.Detect('ifl')

# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:


text:
<?php
/**
 * apply_support view
 *
 */
$today = new DateTime;
?>

Applicant Messages and Support

<?php
if ($count = $applicant->unreadMessageCount()) { ?>

You have <?php print $count; ?> unread messages.

<?php
}?>
<a href='<?php print $this->controller->applyPath('support/new'); ?>'>Create a new message

<?php
if (count($threads)) { ?>

Message	Last Message	Messages

  <?php
  foreach ($threads as $thread) { ?>
          <tr class='<?php
    if ($thread->hasUnreadMessage(\Jazzee\Entity\Message::PROGRAM)) {
      print 'unread';
    } else {
      print 'read';
    }
    ?>'>
            <?php print $thread->getSubject(); ?>

<a href='<?php print $this->controller->applyPath('support/single/' . $thread->getId()); ?>'><?php print strip_tags(substr($thread->getLastMessage()->getText(), 0, 100)); ?>
              <?php
              if (strlen($thread->getLastMessage()->getText()) > 100) {
                print '...';
              }
              ?>

              <?php
              if ($thread->getLastMessage()->getSender() == \Jazzee\Entity\Message::APPLICANT) { ?>
                From you
                <?php
              } else {?>
                From your program
              <?php
              }
              if ($thread->getCreatedAt()->diff($today)->days > 0) {
                print $thread->getCreatedAt()->diff($today)->days . ' days ago';
              } else {
                print 'less than one day ago';
              }?>

    <?php
    print $thread->getMessageCount() . ' total and ';
    print $thread->getUnreadMessageCount(\Jazzee\Entity\Message::PROGRAM) . ' new messages';
    ?>

  <?php
  } //end foreach threads   ?>

  <?php
} //enf if $threads


text:
Selected posts

    {% strip %}
      {% assign counter = 0 %}
      {% for post in site.data.posts-selected %}
        {% if counter < 4 %}
          {% if page.url contains post.url %}{% else %}
            {% assign counter = counter | plus: 1 %}

              {{ post.title }}

          {% endif %}
        {% endif %}
      {% endfor %}
    {% endstrip %}


text:
package com.epai.contract.model.profit;

import com.epai.contract.rpc.CommonResponse;

/**
 * @Author jihua.li
 * @Date 2017/3/25 11:42
 */
public class ReturnProfitResponse extends CommonResponse{

    private int rowKey;
    private ReturnProfit returnProfit;

    public int getRowKey() {
        return rowKey;
    }

    public void setRowKey(int rowKey) {
        this.rowKey = rowKey;
    }

    public ReturnProfit getReturnProfit() {
        return returnProfit;
    }

    public void setReturnProfit(ReturnProfit returnProfit) {
        this.returnProfit = returnProfit;
    }
}


text:
start crypTunnel 80 localhost 60000 *abc[x30]
start crypTunnel 60000 localhost 8080 /r *abc[x30]
start ..\fileStore /p 8080


text:
print "Checking for readline()... ";
if(compile("-lreadline", "#include <readline/readline.h>\nint main(){readline(\"\");}")) {
    print "ok\n";
    $LDFLAGS .= " -lreadline";
    $CFLAGS .= " -DSL_HAS_READLINE";
} else {
    print "failed\n";
}


text:
package com.dianping.zebra.shard.jdbc.parallel;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.junit.Test;

import com.dianping.zebra.shard.jdbc.base.MultiDBBaseTestCase;

public class ParallelPerformanceTest2 extends MultiDBBaseTestCase {

	@Override
	protected String getDBBaseUrl() {
		return "jdbc:h2:mem:";
	}

	@Override
	protected String getCreateScriptConfigFile() {
		return "db-datafiles/createtable-multidb-lifecycle.xml";
	}

	@Override
	protected String getDataFile() {
		return "db-datafiles/data-multidb-lifecycle.xml";
	}

	@Override
	protected String[] getSpringConfigLocations() {
		return new String[] { "ctx-multidb-lifecycle.xml" };
	}

	@Test
	public void test() {
		DataSource ds = (DataSource) context.getBean("zebraDS");

		try {
			Connection conn = ds.getConnection();

			long now = System.currentTimeMillis();
			for(int i = 0 ; i < 10; i++){
				PreparedStatement stmt = conn.prepareStatement("update test set name='testupdate'");
//				stmt.setString(1, "leo3");

				stmt.executeUpdate();
			}

			System.out.println("Time = " + (System.currentTimeMillis() - now));

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

}


text:
package openmods.utils;

import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidStack;
import openmods.Log;

public class TextureUtils {

	public static void bindTextureToClient(ResourceLocation texture) {
		if (texture != null) {
			final Minecraft mc = Minecraft.getMinecraft();
			if (mc != null) {
				mc.renderEngine.bindTexture(texture);
			} else {
				Log.warn("Binding texture to null client.");
			}
		} else {
			Log.warn("Invalid texture location '%s'", texture);
		}
	}

	public static TextureAtlasSprite getFluidTexture(FluidStack fluid) {
		final ResourceLocation textureLocation = fluid.getFluid().getStill(fluid);
		return getTextureAtlasLocation(textureLocation);
	}

	public static TextureAtlasSprite getFluidTexture(Fluid fluid) {
		final ResourceLocation textureLocation = fluid.getStill();
		return getTextureAtlasLocation(textureLocation);
	}

	public static TextureAtlasSprite getTextureAtlasLocation(final ResourceLocation textureLocation) {
		return Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite(textureLocation.toString());
	}

	public static int getRandomNumber() {
		return 4;
	}
}


text:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>EasyAgent Example</title>
</head>
<body>
  <form class="form">
    <input type="text" class="input" placeholder="Search GitHub repositories...">
    <input type="submit" value="Search">
  </form>

  <ul class="result">

  </ul>

  <input type="button" class="fetchMore" style="display: none;" value="fetch more">

  <script src="./bundle.js"></script>
</body>
</html>


text:
        <div class="modal-header <%- type %>">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

<%- error.name %>

<%- error.message %>


text:
package p108

/**
Given an array where elements are sorted in ascending order,
 convert it to a height balanced BST.

Subscribe to see which companies asked this question.
*/

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */

type TreeNode struct {
	Val   int
	Left  *TreeNode
	Right *TreeNode
}

func sortedArrayToBST(nums []int) *TreeNode {
	nlen := len(nums)
	if nlen == 0 {
		return nil
	} else if nlen == 1 {
		return &TreeNode{nums[0], nil, nil}
	}
	mid := nlen / 2
	node := &TreeNode{Val: nums[mid]}
	node.Left = sortedArrayToBST(nums[:mid])
	node.Right = sortedArrayToBST(nums[mid+1:])
	return node
}


text:
<resources>
    <string name="app_name">scala-android</string>
</resources>


text:
package com.datastax.driver.core.exceptions;

/**
 * Thrown when a user type cannot be resolved.
 * <p/>
 * This exception can be raised when the driver is rebuilding
 * its schema metadata, and a user-defined type cannot be completely
 * constructed due to some missing information.
 * It should only appear in the driver logs, never in client code.
 * It shouldn't be considered as a severe error as long as it only
 * appears occasionally.
 */
public class UnresolvedUserTypeException extends DriverException {

    private final String keyspaceName;

    private final String name;

    public UnresolvedUserTypeException(String keyspaceName, String name) {
        super(String.format("Cannot resolve user type %s.%s", keyspaceName, name));
        this.keyspaceName = keyspaceName;
        this.name = name;
    }

    private UnresolvedUserTypeException(String keyspaceName, String name, Throwable cause) {
        super(String.format("Cannot resolve user type %s.%s", keyspaceName, name), cause);
        this.keyspaceName = keyspaceName;
        this.name = name;
    }

    public String getKeyspaceName() {
        return keyspaceName;
    }

    public String getName() {
        return name;
    }

    @Override
    public UnresolvedUserTypeException copy() {
        return new UnresolvedUserTypeException(keyspaceName, name, this);
    }

}


text:
"""
usage - python blastselftargets.py [options]

Performs blastn on each organism for its spacers and writes results in
xml format.

python blastselftargets.py -h will throw up arg references if need be.

Author: @cemyld

DEPENDENCIES:
Biopython
blast+
"""
import argparse
import os
import subprocess

from Bio import SeqIO
from tqdm import tqdm

from util.fetch import fetch

parser = argparse.ArgumentParser(
    description='Blast self targeting spacers and output the files.',
    usage='blast.py [options]'
)
# optional args
parser.add_argument('-i', '--gbdir', required=False, type=str,
                    help='Directory of genbank files', default='gbdir')
parser.add_argument('-o', '--outdir', required=False, type=str,
                    help='Output directory path', default='gbdir/blastoutput')

args = parser.parse_args()

def main(gbdir, outdir):
    os.makedirs(gbdir, exist_ok=True)
    os.makedirs(outdir, exist_ok=True)
    tempq = 'tempquery.fasta'
    tempdb = 'tempdb.fasta'
    for org in tqdm(Organism.objects.all()):
        # get genbank and convert to fasta
        fpath = os.path.join(gbdir, '{}.gb'.format(org.accession))
        if not os.path.isfile(fpath):
            print('\nFetching {} with accession {}'.format(
                org.name,
                org.accession
            ))
            fetch(fpath)
        SeqIO.convert(fpath, 'genbank', tempdb, 'fasta')
        # get spacers of organism and convert to fasta
        spacers = Spacer.objects.filter(loci__organism=org)
        fastatext = ''.join(['>{}\n{}\n'.format(spacer.id, spacer.sequence)
                             for spacer in spacers])
        with open(tempq, 'w') as f:
            f.write(fastatext)
        # run blast and save output
        outpath = os.path.join(outdir, '{}.json'.format(org.accession))
        commandargs = ['blastn', '-query', tempq,
                       '-subject', tempdb, '-out', outpath, '-outfmt', '15']
        subprocess.run(commandargs, stdout=subprocess.DEVNULL)

    os.remove(tempq)
    os.remove(tempdb)

if __name__ == '__main__':
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'phageAPI.settings')
    import django

    django.setup()
    from restapi.models import Organism, Spacer

    # main(args.gbdir, args.outdir)
    main('gbfiles', 'gbfiles/blastoutput')


text:
(function() {
	'use strict';

	// MODULES //

	var // OpenTSDB socket client factory:
		createSocket = require( './../lib' );

	// SCRIPT //

	var socket = createSocket();

	socket
		.host( '192.168.92.111' )
		.port( 4243 )
		.strict( false );

	socket.on( 'error', onError );
	socket.on( 'close', onClose );
	socket.on( 'connect', onConnect );

	connect();

	return;

	// LISTENERS //

	function onError( error ) {
		console.error( error.message );
		console.error( error.stack );
	}

	function onClose() {
		console.log( '...attempting to reconnect in 2 seconds...' );
		setTimeout( function reconnect() {
			connect();
		}, 2000 );
	}

	function onConnect() {
		for ( var i = 0; i < 100; i++ ) {
			write( i );
		}
	}

	// FUNCTIONS //

	function connect() {
		socket.connect();
	}

	function write( idx ) {
		setTimeout( onTimeout, 1000*idx );
		return;

		function onTimeout() {
			if ( socket.status() ) {
				socket.write( newLine(), onWrite );
			}
		}
	}

	function newLine() {
		var metric = 'cpu.utilization',
			timestamp = Date.now(),
			value = Math.random(),
			line = '';

		line += 'put ';
		line += metric + ' ';
		line += timestamp + ' ';
		line += value + ' ';
		line += 'beep=boop ';
		line += 'foo=bar';
		line += '\n';

		return line;
	}

	function onWrite() {
		console.log( '...data written to socket...' );
	}

})();


text:
#ifndef MANSOS_ENERGY_H
#define MANSOS_ENERGY_H

#include <timing.h>

//
// List all potential energy consumers in the system
//
typedef enum {
    ENERGY_CONSUMER_MCU,
    ENERGY_CONSUMER_LPM,
    ENERGY_CONSUMER_LED_RED,
    ENERGY_CONSUMER_LED_GREEN,
    ENERGY_CONSUMER_LED_BLUE,
    ENERGY_CONSUMER_RADIO_TX,
    ENERGY_CONSUMER_RADIO_RX,
    ENERGY_CONSUMER_FLASH_WRITE,
    ENERGY_CONSUMER_FLASH_READ,
    ENERGY_CONSUMER_SENSORS,
    ENERGY_CONSUMER_SERIAL,

    TOTAL_ENERGY_CONSUMERS
} EnergyConsumer_t;

// TODO: ADC, I2C, SPI, watchdog, non-floating GPIO pins?

// Note: the current energy stats gathering cannot handle nested interrupts!

typedef struct EnergyStats_s {
    uint32_t totalTicks;
    uint32_t lastTicks;
    bool on;
} EnergyStats_t;

extern volatile EnergyStats_t energyStats[TOTAL_ENERGY_CONSUMERS];

#if USE_ENERGY_STATS

void energyConsumerOn(EnergyConsumer_t type);
void energyConsumerOff(EnergyConsumer_t type);

static inline void energyConsumerSet(EnergyConsumer_t type, uint8_t on) {
    if (on) energyConsumerOn(type);
    else energyConsumerOff(type);
}

//
// When interrupts are disabled, use TAR directly
//
#define energyConsumerOnNoints(type)                      \
    {                                                     \
        const uint16_t _start_time = ALARM_TIMER_READ();  \
        energyStats[type].on = true

#define energyConsumerOffNoints(type) {                                 \
        const uint_t _time_diff = ALARM_TIMER_READ() - _start_time;     \
        energyStats[type].totalTicks += convertAlarmTimerToMs(_time_diff);  \
        energyStats[type].on = false;                                   \
    }                                                                   \
    }

//
// When measuring IN interrupt, use TAR *and* account it if not already on
//
#define energyConsumerOnIRQ(type)                       \
    bool _energy_consumer_off = !energyStats[type].on;  \
    energyConsumerOnNoints(type);

#define energyConsumerOffIRQ(type)                             \
    if (_energy_consumer_off) energyConsumerOffNoints(type);   \

#else

#define energyConsumerOn(type)         // nothing
#define energyConsumerOff(type)         // nothing
#define energyConsumerSet(type, value) // nothing

#define energyConsumerOnNoints(type)   // nothing
#define energyConsumerOffNoints(type)  // nothing

#define energyConsumerOnIRQ(type)      // nothing
#define energyConsumerOffIRQ(type)     // nothing

#endif

void energyStatsDump(void);

#endif