text:
const express =  require('express');
const app = express();
const mysql = require('mysql');
const bodyParser = require('body-parser');
const sqlConnection = require('./database');
const socketIo = require("socket.io");

//const cors = require('cors');
var allowedOrigins = "http://localhost:8081";
var corsOptions = {
  origin: 'http://localhost:8081',
  optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
};
// app.use(function (req, res, next) {
//     res.header('Access-Control-Allow-Origin', allowedOrigins);
//     res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept-Type');
//     res.header('Access-Control-Allow-Credentials', 'true');
//     next();
// });
//var io = require('socket.io').listen(server);//(server, {origins: allowedOrigins});
//app.use(cors(corsOptions));
app.use(bodyParser.json());
app.post('/user_check_in', (req, res) => {
    console.log('youre in');
    console.log(req);
    var user_id = req.body.user_id;
    var table_id = req.body.table_id;
    var restaurant_id = req.body.restaurant_id;
    var email = req.body.email;
    var phone_number = req.body.phone_number;
    let connection = sqlConnection.createConnection();
    let check_query = 'SELECT * FROM user_table WHERE id='+user_id+';';
    connection.query(check_query, function(err, result) {
       if(err) {
        console.log(err);
	res.status(503);
	}
       if(result) {
          let select_query = 'SELECT name, price FROM food WHERE restaurant_id=' +restaurant_id +";";
          connection.query(select_query, function(err, result)  {
                if(err) {
                   console.log(err);
                   res.status(503);
                } else if(!result) {
                    res.json("No results");
                } else {
                    res.json(result);
                }

            });
       } else {
            let query = 'INSERT INTO user_table (id, table_id,email,phone_number) VALUES (' + user_id +',' + table_id +',"'+email +'",'+ phone_number +');'
    connection.query(query, function(err, result) {
        if(!err) {
            let select_query = 'SELECT name, price FROM food WHERE restaurant_id=' +restaurant_id +";";
            connection.query(select_query, function(err, result)  {
                if(err) {
                   console.log(err);
                   res.status(503);
                } else if(!result) {
                    res.json("No results");
                } else {
                    res.json(result);
                }

            });
        }
        else {
            console.log(err);
        }
    });
         }
    })

});

var server = require('http').createServer(app);
var io = socketIo(server);//(server, {origins: allowedOrigins});

app.post('/add_order', (req, res) => {
    //
    io.emit("ServerNotifyNewOrder", res);

});

app.post('/user_check_out',  (req,res) => {
    let user_id = req.body.user_id;
    let query = 'SELECT u_t.table_id, r_t.total_bill FROM user_table u_t, restaurant_table r_t WHERE u_t.id=' + user_id + ' AND u_t.table_id=r_t.id;';
    let connection = sqlConnection.createConnection();
    connection.query(query, function(err, result) {
        if(err) {
            console.log(err);
            res.status(503);
         } else if(!result) {
             res.json("No results");
         } else {
	    console.log(result);
            io.emit("ServerNotifyForPayment",result);
         }
        });
});

io.on("ServerConfirmPayment", function(data) {
    let query = 'SELECT u_t.id, r_t.total_bill FROM user_table u_t, restaurant_table r_t WHERE u_t.table_id=' + data +' AND r_t.id=' + table_id+';';
    let connection = sqlConnection.createConnection();
    connection.query(query, function(err, result) {
        if(err) {
            console.log(err);
            res.status(503);
         } else if(!result) {
             res.json("No results");
         } else {
             //make API call to worldpay
             var https = require('https');
             let user_id = result.id;
             let total_bill = result.total_bill;
             let developerId = 12345678;
             let version = "1.0";
             let secureNetId = "8011038";
             let secureKey = "DvAdFBTiBODp";
             let url = 'https://gwapi.demo.securenet.com/api/Payments/Charge'
             let payment_id = 1;
             payload = {
                amount: total_bill,
                paymentVaultToken: {
                  customerId: user_id,
                  paymentMethodId: '1'
                },
                developerApplication: {
                  developerId: 12345678,
                  version: '1.0'
                }
              };
              var json = JSON.stringify(payload);
              var options = {
                host: 'gwapi.demo.securenet.com',
                port: 443,
                path: '/api/Payments/Charge',
                method: 'POST',
                headers: {
                  'Content-Type': 'application/json',
                  'Content-Length': Buffer.byteLength(json, 'utf8'),
                  'Authorization': 'Basic ' + new Buffer(secureNetId + ':' + secureKey).toString('base64')
                }
              };
              var req = https.request(options, function(res) {
                var body = '';
                res.on('data', function(d) { body += d; });
                res.on('end', function () {
                  var r = JSON.parse(body);
                  console.log("http response code: ", res.statusCode);
                });
              });

              req.on('error', function(e) { console.error(e); });
              req.write(json);
              req.end();

         }
        });

});

io.on('connection',function(socket){
    console.log("A user is connected");
});

server.listen(3333);
console.log('server up on 3333')

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) 2016-2020 The Gulden developers
// Authored by: Willem de Jonge (willem@isnapp.nl)
// Modifications by: Malcolm MacLeod (mmacleod@gmx.com)
// Distributed under the GULDEN software license, see the accompanying
// file COPYING

#include "witness_operations.h"

#include <stdexcept>
#include <numeric>
#include <algorithm>
#include <boost/uuid/uuid_io.hpp>
#include <cmath>
#include <inttypes.h>
#include "wallet.h"
#include "validation/witnessvalidation.h"
#include "consensus/consensus.h"
#include "consensus/validation.h"
#include "witnessutil.h"
#include "coincontrol.h"
#include "net.h"
#include "alert.h"
#include "appname.h"
#include "utilmoneystr.h"
#include "wallet.h"

witnessOutputsInfoVector getCurrentOutputsForWitnessAccount(CAccount* forAccount)
{
    std::map<COutPoint, Coin> allWitnessCoins;
    if (!getAllUnspentWitnessCoins(chainActive, Params(), chainActive.Tip(), allWitnessCoins))
        throw std::runtime_error("Failed to enumerate all witness coins.");

    witnessOutputsInfoVector matchedOutputs;
    for (const auto& [outpoint, coin] : allWitnessCoins)
    {
        if (IsMine(*forAccount, coin.out))
        {
            matchedOutputs.push_back(std::tuple(coin.out, coin.nHeight, coin.nTxIndex, outpoint));
        }
    }
    return matchedOutputs;
}

void extendwitnessaddresshelper(CAccount* fundingAccount, witnessOutputsInfoVector unspentWitnessOutputs, CWallet* pwallet, CAmount requestedAmount, uint64_t requestedLockPeriodInBlocks, std::string* pTxid, CAmount* pFee)
{
    AssertLockHeld(cs_main);
    AssertLockHeld(pwallet->cs_wallet);

    if (unspentWitnessOutputs.size() > 1)
        throw witness_error(witness::RPC_INVALID_ADDRESS_OR_KEY, strprintf("Address has too many witness outputs cannot extend "));

    if (requestedAmount < (gMinimumWitnessAmount*COIN))
        throw witness_error(witness::RPC_TYPE_ERROR, strprintf("Witness amount must be %d or larger", gMinimumWitnessAmount));

    if (requestedLockPeriodInBlocks > MaximumWitnessLockLength())
        throw witness_error(witness::RPC_INVALID_PARAMETER, "Maximum lock period of 3 years exceeded.");

    if (requestedLockPeriodInBlocks < MinimumWitnessLockLength())
        throw witness_error(witness::RPC_INVALID_PARAMETER, "Minimum lock period of 1 month exceeded.");

    // Add a small buffer to give us time to enter the blockchain
    if (requestedLockPeriodInBlocks == MinimumWitnessLockLength())
        requestedLockPeriodInBlocks += 50;

    // Check for immaturity
    const auto& [currentWitnessTxOut, currentWitnessHeight, currentWitnessTxIndex, currentWitnessOutpoint] = unspentWitnessOutputs[0];
    //fixme: (PHASE5) - Minor code cleanup.
    //This check should go through the actual chain maturity stuff (via wtx) and not calculate maturity directly.
    if (chainActive.Tip()->nHeight - currentWitnessHeight < (uint64_t)(COINBASE_MATURITY))
        throw witness_error(witness::RPC_MISC_ERROR, "Cannot perform operation on immature transaction, please wait for transaction to mature and try again");

    // Check type (can't extend script type, must witness once or renew after phase 4 activated)
    if (currentWitnessTxOut.GetType() != CTxOutType::PoW2WitnessOutput)
        throw witness_error(witness::RPC_TYPE_ERROR, "Witness has to be type POW2WITNESS");

    // Calculate existing lock period
    CTxOutPoW2Witness currentWitnessDetails;
    GetPow2WitnessOutput(currentWitnessTxOut, currentWitnessDetails);
    uint64_t remainingLockDurationInBlocks = GetPoW2RemainingLockLengthInBlocks(currentWitnessDetails.lockUntilBlock, chainActive.Tip()->nHeight);
    if (remainingLockDurationInBlocks == 0)
    {
        throw witness_error(witness::RPC_INVALID_PARAMETER, "PoW² witness has already unlocked so cannot be extended.");
    }

    if (requestedLockPeriodInBlocks < remainingLockDurationInBlocks)
    {
        throw witness_error(witness::RPC_INVALID_PARAMETER, strprintf("New lock period [%d] does not exceed remaining lock period [%d]", requestedLockPeriodInBlocks, remainingLockDurationInBlocks));
    }

    if (requestedAmount < currentWitnessTxOut.nValue)
    {
        throw witness_error(witness::RPC_INVALID_PARAMETER, strprintf("New amount [%d] is smaller than current amount [%d]", requestedAmount, currentWitnessTxOut.nValue));
    }

    // Enforce minimum weight
    int64_t newWeight = GetPoW2RawWeightForAmount(requestedAmount, chainActive.Height(), requestedLockPeriodInBlocks);
    if (newWeight < gMinimumWitnessWeight)
    {
        throw witness_error(witness::RPC_INVALID_PARAMETER, "PoW² witness has insufficient weight.");
    }

    // Enforce new weight > old weight
    uint64_t notUsed1, notUsed2;
    int64_t oldWeight = GetPoW2RawWeightForAmount(currentWitnessTxOut.nValue, chainActive.Height(), GetPoW2LockLengthInBlocksFromOutput(currentWitnessTxOut, currentWitnessHeight, notUsed1, notUsed2));
    if (newWeight <= oldWeight)
    {
        throw witness_error(witness::RPC_INVALID_PARAMETER, strprintf("New weight [%d] does not exceed old weight [%d].", newWeight, oldWeight));
    }

    // Find the account for this address
    CAccount* witnessAccount = pwallet->FindBestWitnessAccountForTransaction(currentWitnessTxOut);

    if (!witnessAccount)
        throw witness_error(witness::RPC_MISC_ERROR, "Could not locate account for address");
    if ((!witnessAccount->IsPoW2Witness()) || witnessAccount->IsFixedKeyPool())
    {
        throw witness_error(witness::RPC_MISC_ERROR, "Cannot extend a witness-only account as spend key is required to do this.");
    }

    // Finally attempt to create and send the witness transaction.
    CReserveKeyOrScript reservekey(pwallet, fundingAccount, KEYCHAIN_CHANGE);
    std::string reasonForFail;
    CAmount transactionFee;
    CMutableTransaction extendWitnessTransaction(CTransaction::SEGSIG_ACTIVATION_VERSION);
    {
        // Add the existing witness output as an input
        pwallet->AddTxInput(extendWitnessTransaction, CInputCoin(currentWitnessOutpoint, currentWitnessTxOut, true, false, currentWitnessHeight, currentWitnessTxIndex), false);

        // Add new witness output
        CTxOut extendedWitnessTxOutput;
        extendedWitnessTxOutput.SetType(CTxOutType::PoW2WitnessOutput);
        // As we are extending the address we reset the "lock from" and we set the "lock until" everything else except the value remains unchanged.
        extendedWitnessTxOutput.output.witnessDetails.lockFromBlock = 0;
        extendedWitnessTxOutput.output.witnessDetails.lockUntilBlock = chainActive.Tip()->nHeight + requestedLockPeriodInBlocks;
        extendedWitnessTxOutput.output.witnessDetails.spendingKeyID = currentWitnessDetails.spendingKeyID;
        extendedWitnessTxOutput.output.witnessDetails.witnessKeyID = currentWitnessDetails.witnessKeyID;
        extendedWitnessTxOutput.output.witnessDetails.failCount = currentWitnessDetails.failCount;
        extendedWitnessTxOutput.output.witnessDetails.actionNonce = currentWitnessDetails.actionNonce+1;
        extendedWitnessTxOutput.nValue = requestedAmount;
        extendWitnessTransaction.vout.push_back(extendedWitnessTxOutput);

        // Fund the additional amount in the transaction (including fees)
        int changeOutputPosition = 1;
        std::set<int> subtractFeeFromOutputs; // Empty - we don't subtract fee from outputs
        CCoinControl coincontrol;
        if (!pwallet->FundTransaction(fundingAccount, extendWitnessTransaction, transactionFee, changeOutputPosition, reasonForFail, false, subtractFeeFromOutputs, coincontrol, reservekey))
        {
            throw witness_error(witness::RPC_MISC_ERROR, strprintf("Failed to fund transaction [%s]", reasonForFail.c_str()));
        }
    }

    uint256 extendTransactionHash;
    {
        LOCK2(cs_main, pwallet->cs_wallet);
        if (!pwallet->SignAndSubmitTransaction(reservekey, extendWitnessTransaction, reasonForFail, &extendTransactionHash))
        {
            throw witness_error(witness::RPC_MISC_ERROR, strprintf("Failed to commit transaction [%s]", reasonForFail.c_str()));
        }
    }

    // Set result parameters
    if (pTxid != nullptr)
        *pTxid = extendTransactionHash.GetHex();
    if (pFee != nullptr)
        *pFee = transactionFee;
}

void fundwitnessaccount(CWallet* pwallet, CAccount* fundingAccount, CAccount* witnessAccount, CAmount amount, uint64_t requestedPeriodInBlocks, bool fAllowMultiple, std::string* pTxid, CAmount* pFee)
{
    if (!IsPow2Phase2Active(chainActive.Tip()))
    {
        throw witness_error(witness::RPC_MISC_ERROR, strprintf("Can't create witness accounts before phase 2 activates"));
    }

    std::vector<CAmount> amounts;
    LOCK(cs_main);

    // For the sake of testnet we turn off 'splitting' for very short lock periods as it was triggering some testnet specific 'short period' bugs that aren't worth fixing for mainnet (where they can't occur)
    if (IsSegSigEnabled(chainActive.TipPrev()) && requestedPeriodInBlocks > 1000)
    {
        CGetWitnessInfo witnessInfo = GetWitnessInfoWrapper();
        amounts = optimalWitnessDistribution(amount, requestedPeriodInBlocks, witnessInfo.nTotalWeightEligibleRaw);
    }
    else
        amounts = { amount };

    fundwitnessaccount(pwallet, fundingAccount, witnessAccount, amounts, requestedPeriodInBlocks, fAllowMultiple, pTxid, pFee);
}

void fundwitnessaccount(CWallet* pwallet, CAccount* fundingAccount, CAccount* witnessAccount, const std::vector<CAmount>& amounts, uint64_t requestedPeriodInBlocks, bool fAllowMultiple, std::string* pTxid, CAmount* pFee)
{
    if (!IsPow2Phase2Active(chainActive.Tip()))
    {
        throw witness_error(witness::RPC_MISC_ERROR, strprintf("Can't create witness accounts before phase 2 activates"));
    }

    if (pwallet == nullptr || witnessAccount == nullptr || fundingAccount == nullptr)
        throw witness_error(witness::RPC_INVALID_PARAMETER, "Require non-null pwallet, fundingAccount, witnessAccount");

    LOCK2(cs_main, pwallet->cs_wallet);

    if (!witnessAccount->IsPoW2Witness())
        throw witness_error(witness::RPC_MISC_ERROR, strprintf("Specified account is not a witness account [%s].", boost::uuids::to_string(witnessAccount->getUUID())));
    if (witnessAccount->m_Type == WitnessOnlyWitnessAccount || !witnessAccount->IsHD())
        throw witness_error(witness::RPC_MISC_ERROR, strprintf("Cannot fund a witness only witness account [%s].", boost::uuids::to_string(witnessAccount->getUUID())));

    const auto& unspentWitnessOutputs = getCurrentOutputsForWitnessAccount(witnessAccount);
    if (unspentWitnessOutputs.size() > 0)
    {
        if (!fAllowMultiple)
            throw std::runtime_error("Account already has an active funded witness address. Perhaps you intended to 'extend' it? See: 'help extendwitnessaccount'");
    }

    if (std::any_of(amounts.begin(), amounts.end(), [](const auto& amount){ return amount < (gMinimumWitnessAmount*COIN); }))
        throw witness_error(witness::RPC_TYPE_ERROR, strprintf("Witness amount must be %d or larger", gMinimumWitnessAmount));

    if (requestedPeriodInBlocks == 0)
        throw witness_error(witness::RPC_TYPE_ERROR, "Invalid number passed for lock period.");

    if (requestedPeriodInBlocks > MaximumWitnessLockLength())
        throw witness_error(witness::RPC_INVALID_PARAMETER, "Maximum lock period of 3 years exceeded.");

    if (requestedPeriodInBlocks < MinimumWitnessLockLength())
        throw witness_error(witness::RPC_INVALID_PARAMETER, "Minimum lock period of 1 month exceeded.");

    // Add a small buffer to give us time to enter the blockchain
    if (requestedPeriodInBlocks == MinimumWitnessLockLength())
        requestedPeriodInBlocks += 50;

    // Enforce minimum weight for each amount
    if (std::any_of(amounts.begin(), amounts.end(), [&](const auto& amount){ return GetPoW2RawWeightForAmount(amount, chainActive.Height(), requestedPeriodInBlocks) < gMinimumWitnessWeight; }))
    {
        throw witness_error(witness::RPC_INVALID_PARAMETER, "PoW² witness has insufficient weight.");
    }

    // Finally attempt to create and send the witness transaction.
    CPoW2WitnessDestination destinationPoW2Witness;
    destinationPoW2Witness.lockFromBlock = 0;
    destinationPoW2Witness.lockUntilBlock = chainActive.Tip()->nHeight + requestedPeriodInBlocks;
    destinationPoW2Witness.failCount = 0;
    destinationPoW2Witness.actionNonce = 0;
    {
        CReserveKeyOrScript keyWitness(pactiveWallet, witnessAccount, KEYCHAIN_WITNESS);
        CPubKey pubWitnessKey;
        if (!keyWitness.GetReservedKey(pubWitnessKey))
            throw witness_error(witness::RPC_INVALID_ADDRESS_OR_KEY, "Error allocating witness key for witness account.");

        //We delibritely return the key here, so that if we fail we won't leak the key.
        //The key will be marked as used when the transaction is accepted anyway.
        keyWitness.ReturnKey();
        destinationPoW2Witness.witnessKey = pubWitnessKey.GetID();
    }
    {
        //Code should be refactored to only call 'KeepKey' -after- success, a bit tricky to get there though.
        CReserveKeyOrScript keySpending(pactiveWallet, witnessAccount, KEYCHAIN_SPENDING);
        CPubKey pubSpendingKey;
        if (!keySpending.GetReservedKey(pubSpendingKey))
            throw witness_error(witness::RPC_INVALID_ADDRESS_OR_KEY, "Error allocating spending key for witness account.");

        //We delibritely return the key here, so that if we fail we won't leak the key.
        //The key will be marked as used when the transaction is accepted anyway.
        keySpending.ReturnKey();
        destinationPoW2Witness.spendingKey = pubSpendingKey.GetID();
    }

    CAmount transactionFee;
    std::string strError;
    std::vector<CRecipient> vecSend;
    int nChangePosRet = -1;

    std::for_each(amounts.begin(), amounts.end(), [&](const CAmount& amount){
        CRecipient recipient = ( IsSegSigEnabled(chainActive.TipPrev()) ? ( CRecipient(GetPoW2WitnessOutputFromWitnessDestination(destinationPoW2Witness), amount, false) ) : ( CRecipient(GetScriptForDestination(destinationPoW2Witness), amount, false) ) ) ;
        if (!IsSegSigEnabled(chainActive.TipPrev()))
        {
            // We have to copy this anyway even though we are using a CSCript as later code depends on it to grab the witness key id.
            recipient.witnessDetails.witnessKeyID = destinationPoW2Witness.witnessKey;
        }

        //NB! Setting this is -super- important, if we don't then encrypted wallets may fail to witness.
        recipient.witnessForAccount = witnessAccount;
        vecSend.push_back(recipient);
    });

    CWalletTx wtx;
    CReserveKeyOrScript reservekey(pwallet, fundingAccount, KEYCHAIN_CHANGE);
    if (!pwallet->CreateTransaction(fundingAccount, vecSend, wtx, reservekey, transactionFee, nChangePosRet, strError))
    {
        throw witness_error(witness::RPC_WALLET_ERROR, strError);
    }

    CValidationState state;
    if (!pwallet->CommitTransaction(wtx, reservekey, g_connman.get(), state))
    {
        strError = strprintf("Error: The transaction was rejected! Reason given: %s", state.GetRejectReason());
        throw witness_error(witness::RPC_WALLET_ERROR, strError);
    }

    // Set result parameters
    if (pTxid != nullptr)
        *pTxid = wtx.GetHash().GetHex();
    if (pFee != nullptr)
        *pFee = transactionFee;
}

void renewwitnessaccount(CWallet* pwallet, CAccount* fundingAccount, CAccount* witnessAccount, std::string* pTxid, CAmount* pFee)
{
    if (pwallet == nullptr || witnessAccount == nullptr || fundingAccount == nullptr)
        throw witness_error(witness::RPC_INVALID_PARAMETER, "Require non-null pwallet, fundingAccount, witnessAccount");

    LOCK2(cs_main, pwallet->cs_wallet);

    if (pwallet->IsLocked()) {
        throw std::runtime_error("Wallet locked");
    }

    if ((!witnessAccount->IsPoW2Witness()) || witnessAccount->IsFixedKeyPool())
    {
        throw witness_error(witness::RPC_MISC_ERROR, "Cannot renew a witness-only account as spend key is required to do this.");
    }

    std::string strError;
    CMutableTransaction tx(CURRENT_TX_VERSION_POW2);
    CReserveKeyOrScript changeReserveKey(pactiveWallet, fundingAccount, KEYCHAIN_EXTERNAL);
    CAmount transactionFee;
    if (!pwallet->PrepareRenewWitnessAccountTransaction(fundingAccount, witnessAccount, changeReserveKey, tx, transactionFee, strError))
    {
        throw std::runtime_error(strprintf("Failed to renew witness [%s]", strError.c_str()));
    }

    uint256 upgradeTransactionHash;
    if (!pwallet->SignAndSubmitTransaction(changeReserveKey, tx, strError, &upgradeTransactionHash))
    {
        LogPrintf("renewwitnessaccount Failed to sign transaction [%s]", strError.c_str());
        throw std::runtime_error(strprintf("Failed to sign transaction [%s]", strError.c_str()));
    }

    // Set result parameters
    if (pTxid != nullptr)
        *pTxid = upgradeTransactionHash.GetHex();
    if (pFee != nullptr)
        *pFee = transactionFee;
}

void rotatewitnessaddresshelper(CAccount* fundingAccount, witnessOutputsInfoVector unspentWitnessOutputs, CWallet* pwallet, std::string* pTxid, CAmount* pFee)
{
    if (unspentWitnessOutputs.size() == 0)
        throw witness_error(witness::RPC_INVALID_ADDRESS_OR_KEY, strprintf("Too few witness outputs cannot rotate."));

    // Check for immaturity
    for (const auto& [currentWitnessTxOut, currentWitnessHeight, currentWitnessTxIndex, currentWitnessOutpoint]: unspentWitnessOutputs)
    {
        (unused) currentWitnessTxOut;
        (unused) currentWitnessOutpoint;
        (unused) currentWitnessTxIndex;
        //fixme: (PHASE5) - Minor code cleanup.
        //This check should go through the actual chain maturity stuff (via wtx) and not calculate maturity directly.
        if (chainActive.Tip()->nHeight - currentWitnessHeight < (uint64_t)(COINBASE_MATURITY))
            throw witness_error(witness::RPC_MISC_ERROR, "Cannot perform operation on immature transaction, please wait for transaction to mature and try again");
    }

    // Find the account for this address
    CAccount* witnessAccount = nullptr;
    {
        CTxOutPoW2Witness currentWitnessDetails;
        const auto& currentWitnessTxOut = std::get<0>(unspentWitnessOutputs[0]);
        GetPow2WitnessOutput(currentWitnessTxOut, currentWitnessDetails);
        witnessAccount = pwallet->FindBestWitnessAccountForTransaction(currentWitnessTxOut);
    }
    if (!witnessAccount)
    {
        throw witness_error(witness::RPC_MISC_ERROR, "Could not locate account");
    }
    if ((!witnessAccount->IsPoW2Witness()) || witnessAccount->IsFixedKeyPool())
    {
        throw witness_error(witness::RPC_MISC_ERROR, "Cannot rotate a witness-only account as spend key is required to do this.");
    }

    // Finally attempt to create and send the witness transaction.
    CReserveKeyOrScript reservekey(pwallet, fundingAccount, KEYCHAIN_CHANGE);
    std::string reasonForFail;
    CAmount transactionFee;
    CMutableTransaction rotateWitnessTransaction(CTransaction::SEGSIG_ACTIVATION_VERSION);
    CPubKey pubWitnessKey;
    {
        // Get new witness key
        CReserveKeyOrScript keyWitness(pactiveWallet, witnessAccount, KEYCHAIN_WITNESS);
        if (!keyWitness.GetReservedKey(pubWitnessKey))
        {
            throw witness_error(witness::RPC_INVALID_ADDRESS_OR_KEY, "Error allocating witness key for witness account.");
        }

        //We delibritely return the key here, so that if we fail we won't leak the key.
        //The key will be marked as used when the transaction is accepted anyway.
        keyWitness.ReturnKey();
    }

    // Add all existing outputs as inputs and new outputs
    for (const auto& [currentWitnessTxOut, currentWitnessHeight, currentWitnessTxIndex, currentWitnessOutpoint]: unspentWitnessOutputs)
    {
        // Add input
        pwallet->AddTxInput(rotateWitnessTransaction, CInputCoin(currentWitnessOutpoint, currentWitnessTxOut, true, false, currentWitnessHeight, currentWitnessTxIndex), false);

        // Get witness details
        CTxOutPoW2Witness currentWitnessDetails;
        if (!GetPow2WitnessOutput(currentWitnessTxOut, currentWitnessDetails))
            throw witness_error(witness::RPC_MISC_ERROR, "Failure extracting witness details.");

        // Add rotated output
        CTxOut rotatedWitnessTxOutput;
        rotatedWitnessTxOutput.SetType(CTxOutType::PoW2WitnessOutput);
        rotatedWitnessTxOutput.output.witnessDetails.lockFromBlock = currentWitnessDetails.lockFromBlock;
        // Ensure consistent lock from
        if (rotatedWitnessTxOutput.output.witnessDetails.lockFromBlock == 0)
        {
            rotatedWitnessTxOutput.output.witnessDetails.lockFromBlock = currentWitnessHeight;
        }
        rotatedWitnessTxOutput.output.witnessDetails.lockUntilBlock = currentWitnessDetails.lockUntilBlock;
        rotatedWitnessTxOutput.output.witnessDetails.spendingKeyID = currentWitnessDetails.spendingKeyID;
        rotatedWitnessTxOutput.output.witnessDetails.witnessKeyID = pubWitnessKey.GetID();
        rotatedWitnessTxOutput.output.witnessDetails.failCount = currentWitnessDetails.failCount;
        rotatedWitnessTxOutput.output.witnessDetails.actionNonce = currentWitnessDetails.actionNonce+1;
        rotatedWitnessTxOutput.nValue = currentWitnessTxOut.nValue;
        rotateWitnessTransaction.vout.push_back(rotatedWitnessTxOutput);
    }

    // Fund the additional amount in the transaction (including fees)
    int changeOutputPosition = 1;
    std::set<int> subtractFeeFromOutputs; // Empty - we don't subtract fee from outputs
    CCoinControl coincontrol;
    if (!pwallet->FundTransaction(fundingAccount, rotateWitnessTransaction, transactionFee, changeOutputPosition, reasonForFail, false, subtractFeeFromOutputs, coincontrol, reservekey))
    {
        throw witness_error(witness::RPC_MISC_ERROR, strprintf("Failed to fund transaction [%s]", reasonForFail.c_str()));
    }

    //fixme: (PHASE5) - Minor code cleanup
    //Improve this a bit, we should make this 'atomic'
    //i.e. only perform the action that can't be rolled back (adding the key to the account) if the entire thing succeeds
    //So only after the signing of the transaction is a success
    //Also (low) this shares common code with CreateTransaction() - so it should be factored out into a common helper that both can use.
    CKey privWitnessKey;
    if (!witnessAccount->GetKey(pubWitnessKey.GetID(), privWitnessKey))
    {
        reasonForFail = strprintf("Wallet error, failed to retrieve private witness key.");
        throw witness_error(witness::RPC_MISC_ERROR, strprintf("Failed to fund transaction [%s]", reasonForFail.c_str()));
    }
    if (!pwallet->AddKeyPubKey(privWitnessKey, privWitnessKey.GetPubKey(), *witnessAccount, KEYCHAIN_WITNESS))
    {
        reasonForFail = strprintf("Wallet error, failed to store witness key.");
        throw witness_error(witness::RPC_MISC_ERROR, strprintf("Failed to fund transaction [%s]", reasonForFail.c_str()));
    }

    uint256 rotateTransactionHash;
    {
        LOCK2(cs_main, pactiveWallet->cs_wallet);
        if (!pwallet->SignAndSubmitTransaction(reservekey, rotateWitnessTransaction, reasonForFail, &rotateTransactionHash))
        {
            throw witness_error(witness::RPC_MISC_ERROR, strprintf("Failed to commit transaction [%s]", reasonForFail.c_str()));
        }
    }

    // Set result parameters
    if (pTxid != nullptr)
        *pTxid = rotateTransactionHash.GetHex();
    if (pFee != nullptr)
        *pFee = transactionFee;
}

void rotatewitnessaccount(CWallet* pwallet, CAccount* fundingAccount, CAccount* witnessAccount, std::string* pTxid, CAmount* pFee)
{
    if (pwallet == nullptr || witnessAccount == nullptr || fundingAccount == nullptr)
        throw witness_error(witness::RPC_INVALID_PARAMETER, "Require non-null pwallet, fundingAccount, witnessAccount");

    LOCK2(cs_main, pwallet->cs_wallet);

    if (!IsSegSigEnabled(chainActive.TipPrev()))
        throw std::runtime_error("Cannot use this command before segsig activates");

    if (pwallet->IsLocked()) {
        throw std::runtime_error("Wallet locked");
    }

    if ((!witnessAccount->IsPoW2Witness()) || witnessAccount->IsFixedKeyPool())
    {
        throw witness_error(witness::RPC_MISC_ERROR, "Cannot rotate a witness-only account as spend key is required to do this.");
    }

    const auto& unspentWitnessOutputs = getCurrentOutputsForWitnessAccount(witnessAccount);
    if (unspentWitnessOutputs.size() == 0)
        throw witness_error(witness::RPC_INVALID_ADDRESS_OR_KEY, strprintf("Account does not contain any witness outputs [%s].",
                                                                           boost::uuids::to_string(witnessAccount->getUUID())));

    rotatewitnessaddresshelper(fundingAccount, unspentWitnessOutputs, pwallet, pTxid, pFee);
}

CGetWitnessInfo GetWitnessInfoWrapper()
{
    CGetWitnessInfo witnessInfo;

    CBlock block;
    {
        LOCK(cs_main); // Required for ReadBlockFromDisk as well as GetWitnessInfo.
        if (!ReadBlockFromDisk(block, chainActive.Tip(), Params()))
        {
            std::string strErrorMessage = "Error in GetWitnessInfoWrapper, failed to read block from disk";
            CAlert::Notify(strErrorMessage, true, true);
            LogPrintf("%s", strErrorMessage.c_str());
            throw std::runtime_error(strErrorMessage);
        }
        if (!GetWitness(chainActive, Params(), nullptr, chainActive.Tip()->pprev, block, witnessInfo))
        {
            std::string strErrorMessage = "Error in GetWitnessInfoWrapper, failed to retrieve witness info";
            CAlert::Notify(strErrorMessage, true, true);
            LogPrintf("%s", strErrorMessage.c_str());
            throw std::runtime_error(strErrorMessage);
        }
    }

    return witnessInfo;
}

void EnsureMatchingWitnessCharacteristics(const witnessOutputsInfoVector& unspentWitnessOutputs)
{
    // Properties should beidentical, except lockFromBlock is special.
    // Extending (or initial funding) of a multiple-part witness can result in different lockFromBlock values, which are test as follows:
    // A) All outputs that have a non-zero lockFromBlock should share the same non-zero value.
    // B) All outputs with a zero lockFromBlock should share the same coin height.
    // C) And finally the non-zero value from A and B should be the same.
    // When a new witness is created it enters with a lockFromBlock == 0, which is replaced by the height the tx entered the chain
    // in a later operation (ie. a witness operation, rearrange, renew etc.)
    if (unspentWitnessOutputs.size() > 0)
    {
        CTxOutPoW2Witness witnessDetails0;
        if (!GetPow2WitnessOutput(std::get<0>(unspentWitnessOutputs[0]), witnessDetails0))
            throw std::runtime_error("Failure extracting witness details.");

        // collect values for A and B tests
        uint64_t nonZeroFrom = 0;
        uint64_t nonZeroCoin = 0;
        for (unsigned int i = 0; i < unspentWitnessOutputs.size(); i++) {
            CTxOutPoW2Witness witnessDetails;
            if (!GetPow2WitnessOutput(std::get<0>(unspentWitnessOutputs[i]), witnessDetails))
                throw std::runtime_error("Failure extracting witness details.");
            if (witnessDetails.lockFromBlock != 0)
                nonZeroFrom = witnessDetails.lockFromBlock;
            else
                nonZeroCoin = std::get<1>(unspentWitnessOutputs[i]);

            if (nonZeroFrom != 0 && nonZeroCoin != 0)
                break;
        }

        // test C
        if (nonZeroFrom != 0 && nonZeroCoin != 0 && nonZeroFrom != nonZeroCoin)
            throw std::runtime_error("Multiple addresses with different witness characteristics in account. Use RPC to furter handle this account.");

        for (unsigned int i = 0; i < unspentWitnessOutputs.size(); i++) {
            CTxOutPoW2Witness witnessCompare;
            if (!GetPow2WitnessOutput(std::get<0>(unspentWitnessOutputs[i]), witnessCompare))
                throw std::runtime_error("Failure extracting witness details.");
            if (witnessCompare.lockUntilBlock != witnessDetails0.lockUntilBlock ||
                witnessCompare.spendingKeyID != witnessDetails0.spendingKeyID ||
                witnessCompare.witnessKeyID != witnessDetails0.witnessKeyID ||
                (witnessCompare.lockFromBlock != 0 && witnessCompare.lockFromBlock != nonZeroFrom) || // test A
                (witnessCompare.lockFromBlock == 0 && std::get<1>(unspentWitnessOutputs[i]) != nonZeroCoin)) // test B
            {
                throw std::runtime_error("Multiple addresses with different witness characteristics in account. Use RPC to furter handle this account.");
            }
        }

    }
}

CWitnessAccountStatus GetWitnessAccountStatus(CWallet* pWallet, CAccount* account, CGetWitnessInfo* pWitnessInfo)
{
    WitnessStatus status;

    LOCK2(cs_main, pWallet->cs_wallet);

    CGetWitnessInfo witnessInfo;

    if (chainActive.Height() > 0 && IsPow2Phase5Active(chainActive.Height())) {
        witnessInfo = GetWitnessInfoWrapper();
    }

    // Collect uspent witnesses coins for the account
    std::vector<RouletteItem> accountItems;
    for (const auto& item : witnessInfo.witnessSelectionPoolUnfiltered)
    {
        if (IsMine(*account, item.coin.out))
            accountItems.push_back(item);
    }

    bool haveUnspentWitnessUtxo = accountItems.size() > 0;

    CTxOutPoW2Witness witnessDetails0;
    if (haveUnspentWitnessUtxo && !GetPow2WitnessOutput(accountItems[0].coin.out, witnessDetails0))
        throw std::runtime_error("Failure extracting witness details.");

    uint64_t nLockFromBlock = 0;
    uint64_t nLockUntilBlock = 0;
    uint64_t nLockPeriodInBlocks = accountItems.size() > 0 ? GetPoW2LockLengthInBlocksFromOutput(accountItems[0].coin.out, accountItems[0].coin.nHeight, nLockFromBlock, nLockUntilBlock) : 0;

    const auto& unspentWitnessOutputs = getCurrentOutputsForWitnessAccount(account);
    EnsureMatchingWitnessCharacteristics(unspentWitnessOutputs);

    bool hasUnconfirmedBalance = pactiveWallet->GetUnconfirmedBalance(account, true, true) > 0;
    bool hasImmatureBalance = pactiveWallet->GetImmatureBalance(account, true, true) > 0;
    CAmount lockedBalance = pactiveWallet->GetLockedBalance(account, true);
    bool hasLockedBalance = lockedBalance > 0;
    bool hasMatureBalance = pactiveWallet->GetBalance(account, true, false, true) > 0;

    bool hasBalance = hasUnconfirmedBalance||hasImmatureBalance||hasMatureBalance||hasLockedBalance;

    bool isLocked = haveUnspentWitnessUtxo && IsPoW2WitnessLocked(witnessDetails0, chainActive.Tip()->nHeight);

    uint64_t networkWeight = witnessInfo.nTotalWeightRaw;
    bool isExpired = haveUnspentWitnessUtxo && std::any_of(accountItems.begin(), accountItems.end(), [=](const RouletteItem& ri){
                         return witnessHasExpired(ri.nAge, ri.nWeight, networkWeight);
                     });

    if (!haveUnspentWitnessUtxo && (hasImmatureBalance||hasUnconfirmedBalance||hasLockedBalance))
    {
        status = WitnessStatus::Pending;
    }
    else if (!haveUnspentWitnessUtxo && !hasBalance)
    {
        status = WitnessStatus::Empty;
    }
    else if (!haveUnspentWitnessUtxo && hasMatureBalance && !(hasImmatureBalance || hasUnconfirmedBalance))
    {
        status = WitnessStatus::EmptyWithRemainder;
    }
    else if (haveUnspentWitnessUtxo && hasBalance && isLocked && isExpired)
    {
        status = WitnessStatus::Expired;
    }
    else if (haveUnspentWitnessUtxo && hasBalance && isLocked && !isExpired)
    {
        status = WitnessStatus::Witnessing;
    }
    else if (haveUnspentWitnessUtxo && hasBalance && isLocked && isExpired)
    {
        status = WitnessStatus::Expired;
    }
    else if (haveUnspentWitnessUtxo && hasBalance && !isLocked)
    {
        status = WitnessStatus::Ended;
    }
    else if (haveUnspentWitnessUtxo && !hasBalance && !isLocked)
    {
        status = WitnessStatus::Emptying;
    }
    else
    {
        throw std::runtime_error("Unable to determine witness state.");
    }

    // NOTE: assuming any unconfirmed tx here is a witness; avoid getting the witness bundles and testing those, this will almost always be
    // correct. Any edge cases where this fails will automatically resolve once the tx confirms.
    bool hasUnconfirmedWittnessTx = std::any_of(pWallet->mapWallet.begin(), pWallet->mapWallet.end(), [=](const auto& it){
        const auto& wtx = it.second;
        return account->HaveWalletTx(wtx) && wtx.InMempool();
    });

    // hasUnconfirmedWittnessTx -> renewed, extended ...
    if (status == WitnessStatus::Expired && hasUnconfirmedWittnessTx)
        status = WitnessStatus::Witnessing;

    bool hasScriptLegacyOutput = std::any_of(accountItems.begin(), accountItems.end(), [](const RouletteItem& ri){ return ri.coin.out.GetType() == CTxOutType::ScriptLegacyOutput; });

    std::vector<uint64_t> parts;
    std::transform(accountItems.begin(), accountItems.end(), std::back_inserter(parts), [](const auto& ri) { return ri.nWeight; });

    CWitnessAccountStatus result {
        account,
        status,
        networkWeight,
        //NB! We always want the account weight (even if expired) - otherwise how do we e.g. draw a historical graph of the expected earnings for the expired account?
        std::accumulate(accountItems.begin(), accountItems.end(), uint64_t(0), [](const uint64_t acc, const RouletteItem& ri){ return acc + ri.nWeight; }),
        lockedBalance,
        hasScriptLegacyOutput,
        hasUnconfirmedWittnessTx,
        nLockFromBlock,
        nLockUntilBlock,
        nLockPeriodInBlocks,
        parts
    };

    if (pWitnessInfo && IsPow2Phase3Active(chainActive.Height()))
        *pWitnessInfo = std::move(witnessInfo);

    return result;
}

void redistributeandextendwitnessaccount(CWallet* pwallet, CAccount* fundingAccount, CAccount* witnessAccount, const std::vector<CAmount>& redistributionAmounts, uint64_t requestedLockPeriodInBlocks, std::string* pTxid, CAmount* pFee)
{
    if (pwallet == nullptr || witnessAccount == nullptr || fundingAccount == nullptr)
    {
        throw witness_error(witness::RPC_INVALID_PARAMETER, "Require non-null pwallet, fundingAccount, witnessAccount");
    }

    LOCK2(cs_main, pwallet->cs_wallet);

    if (!IsSegSigEnabled(chainActive.TipPrev()))
    {
        throw std::runtime_error("Segsig not activated");
    }

    if (pwallet->IsLocked())
    {
        throw std::runtime_error("Wallet locked");
    }

    if ((!witnessAccount->IsPoW2Witness()) || witnessAccount->IsFixedKeyPool())
    {
        throw witness_error(witness::RPC_MISC_ERROR, "Cannot operate on witness-only account as spend key is required to do this.");
    }

    const auto& unspentWitnessOutputs = getCurrentOutputsForWitnessAccount(witnessAccount);
    if (unspentWitnessOutputs.size() == 0)
    {
        throw witness_error(witness::RPC_INVALID_ADDRESS_OR_KEY, strprintf("Account does not contain any witness outputs [%s].", boost::uuids::to_string(witnessAccount->getUUID())));
    }

    EnsureMatchingWitnessCharacteristics(unspentWitnessOutputs);

    const auto& [currentWitnessTxOut, currentWitnessHeight, currentWitnessTxIndex, currentWitnessOutpoint] = unspentWitnessOutputs[0];
    (unused)currentWitnessHeight;
    (unused)currentWitnessTxIndex;
    (unused)currentWitnessOutpoint;

    // Get the current witness details
    CTxOutPoW2Witness currentWitnessDetails;
    GetPow2WitnessOutput(currentWitnessTxOut, currentWitnessDetails);

    if (std::any_of(redistributionAmounts.begin(), redistributionAmounts.end(), [](const auto& amount){ return amount < (gMinimumWitnessAmount*COIN); }))
        throw witness_error(witness::RPC_TYPE_ERROR, strprintf("Witness amount must be %d or larger", gMinimumWitnessAmount));

    uint64_t remainingLockDurationInBlocks = GetPoW2RemainingLockLengthInBlocks(currentWitnessDetails.lockUntilBlock, chainActive.Tip()->nHeight);
    if (remainingLockDurationInBlocks == 0)
    {
        throw witness_error(witness::RPC_INVALID_PARAMETER, "PoW² witness has already unlocked.");
    }

    // extend specifics
    if (requestedLockPeriodInBlocks != 0)
    {
        if (requestedLockPeriodInBlocks > MaximumWitnessLockLength())
        {
            throw witness_error(witness::RPC_INVALID_PARAMETER, "Maximum lock period of 3 years exceeded.");
        }

        if (requestedLockPeriodInBlocks < MinimumWitnessLockLength())
        {
            throw witness_error(witness::RPC_INVALID_PARAMETER, "Minimum lock period of 1 month exceeded.");
        }

        // Add a small buffer to give us time to enter the blockchain
        if (requestedLockPeriodInBlocks == MinimumWitnessLockLength())
        {
            requestedLockPeriodInBlocks += 50;
        }

        if (requestedLockPeriodInBlocks < remainingLockDurationInBlocks)
        {
            throw witness_error(witness::RPC_INVALID_PARAMETER, strprintf("New lock period [%d] does not exceed remaining lock period [%d]", requestedLockPeriodInBlocks, remainingLockDurationInBlocks));
        }

        // Enforce minimum weight for each amount
        auto tooSmallTest = [&] (const auto& amount){ return GetPoW2RawWeightForAmount(amount, chainActive.Height(), requestedLockPeriodInBlocks) < gMinimumWitnessWeight; };
        bool witnessAmountTooSmall = std::any_of(redistributionAmounts.begin(), redistributionAmounts.end(), tooSmallTest);
        if (witnessAmountTooSmall)
        {
            throw witness_error(witness::RPC_TYPE_ERROR, strprintf("Witness amount must be %d or larger", gMinimumWitnessAmount));
        }

        // Enforce new combined weight > old combined weight
        const CGetWitnessInfo witnessInfo = GetWitnessInfoWrapper();
        uint64_t dummyLockFrom, dummyLockUntil;
        uint64_t oldLockPeriod = GetPoW2LockLengthInBlocksFromOutput(currentWitnessTxOut, currentWitnessHeight, dummyLockFrom, dummyLockUntil);
        std::vector<CAmount> oldAmounts;
        std::transform(unspentWitnessOutputs.begin(), unspentWitnessOutputs.end(), std::back_inserter(oldAmounts), [](const auto& it) { return std::get<0>(it).nValue; });
        uint64_t oldCombinedWeight = combinedWeight(oldAmounts, currentWitnessHeight, oldLockPeriod);
        uint64_t newCombinedWeight = combinedWeight(redistributionAmounts, currentWitnessHeight, requestedLockPeriodInBlocks);
        if (oldCombinedWeight >= newCombinedWeight)
        {
            throw witness_error(witness::RPC_TYPE_ERROR, strprintf("New combined witness weight (%" PRIu64 ") must exceed old (%" PRIu64 ")", newCombinedWeight, oldCombinedWeight));
        }
    }

    // Check for immaturity
    for ( const auto& [currentWitnessTxOut, currentWitnessHeight, currentWitnessTxIndex, currentWitnessOutpoint] : unspentWitnessOutputs )
    {
        (unused) currentWitnessTxOut;
        (unused) currentWitnessOutpoint;
        (unused) currentWitnessTxIndex;
        //fixme: (PHASE5) - Minor code cleanup.
        //This check should go through the actual chain maturity stuff (via wtx) and not calculate maturity directly.
        if (chainActive.Tip()->nHeight - currentWitnessHeight < (uint64_t)(COINBASE_MATURITY))
        {
            throw witness_error(witness::RPC_MISC_ERROR, "Cannot perform operation on immature transaction, please wait for transaction to mature and try again");
        }
    }

    // Check type (can't extend script type, must witness once or renew/upgrade after phase 4 activated)
    if (std::any_of(unspentWitnessOutputs.begin(), unspentWitnessOutputs.end(), [](const auto& it){ return std::get<0>(it).GetType() !=  CTxOutType::PoW2WitnessOutput; }))
    {
        throw witness_error(witness::RPC_TYPE_ERROR, "Witness has to be type POW2WITNESS, renew or upgrade account");
    }

    // Check that total of new value is at least old total
    CAmount redistributionTotal = std::accumulate(redistributionAmounts.begin(), redistributionAmounts.end(), CAmount(0), [](const CAmount acc, const CAmount amount){ return acc + amount; });
    CAmount oldTotal = std::accumulate(unspentWitnessOutputs.begin(), unspentWitnessOutputs.end(), CAmount(0), [](const CAmount acc, const auto& it){
        const CTxOut& txOut = std::get<0>(it);
        return acc + txOut.nValue;
    });
    if (redistributionTotal < oldTotal)
    {
        throw witness_error(witness::RPC_INVALID_PARAMETER, strprintf("New amount [%s] is smaller than current amount [%s]", FormatMoney(redistributionTotal), FormatMoney(oldTotal)));
    }

    // Create the redistribution transaction
    CReserveKeyOrScript reservekey(pwallet, fundingAccount, KEYCHAIN_CHANGE);
    std::string reasonForFail;
    CAmount transactionFee;
    CMutableTransaction witnessTransaction(CTransaction::SEGSIG_ACTIVATION_VERSION);
    {

        uint64_t highestActionNonce = 0;
        uint64_t highestFailCount = 0;

        // Add all original outputs as inputs
        for (const auto& [currentWitnessTxOut, currentWitnessHeight, currentWitnessTxIndex, currentWitnessOutpoint]: unspentWitnessOutputs)
        {
            pwallet->AddTxInput(witnessTransaction, CInputCoin(currentWitnessOutpoint, currentWitnessTxOut, true, false, currentWitnessHeight, currentWitnessTxIndex), false);

            CTxOutPoW2Witness details;
            if (!GetPow2WitnessOutput(currentWitnessTxOut, details))
            {
                throw witness_error(witness::RPC_MISC_ERROR, "Failure extracting witness details.");
            }
            if (details.actionNonce > highestActionNonce)
                highestActionNonce = details.actionNonce;
            if (details.failCount > highestFailCount)
                highestFailCount = details.failCount;
        }

        // Add new witness outputs
        for (const CAmount& distAmount : redistributionAmounts)
        {
            CTxOut distTxOutput;
            distTxOutput.SetType(CTxOutType::PoW2WitnessOutput);
             if (requestedLockPeriodInBlocks != 0)
             {
                 // extend
                 distTxOutput.output.witnessDetails.lockFromBlock = 0;
                 distTxOutput.output.witnessDetails.lockUntilBlock = chainActive.Tip()->nHeight + requestedLockPeriodInBlocks;
             }
             else
             {
                 // rearrange
                 distTxOutput.output.witnessDetails.lockFromBlock = currentWitnessDetails.lockFromBlock;
                 distTxOutput.output.witnessDetails.lockUntilBlock = currentWitnessDetails.lockUntilBlock;
             }
            distTxOutput.output.witnessDetails.spendingKeyID = currentWitnessDetails.spendingKeyID;
            distTxOutput.output.witnessDetails.witnessKeyID = currentWitnessDetails.witnessKeyID;
            distTxOutput.output.witnessDetails.failCount = highestFailCount;
            distTxOutput.output.witnessDetails.actionNonce = highestActionNonce + 1;
            distTxOutput.nValue = distAmount;
            witnessTransaction.vout.push_back(distTxOutput);
        }

        // Fund the additional amount in the transaction (including fees)
        int changeOutputPosition = 1;
        std::set<int> subtractFeeFromOutputs; // Empty - we don't subtract fee from outputs
        CCoinControl coincontrol;
        if (!pwallet->FundTransaction(fundingAccount, witnessTransaction, transactionFee, changeOutputPosition, reasonForFail, false, subtractFeeFromOutputs, coincontrol, reservekey))
        {
            throw witness_error(witness::RPC_MISC_ERROR, strprintf("Failed to fund transaction [%s]", reasonForFail.c_str()));
        }
    }

    uint256 finalTransactionHash;
    {
        LOCK2(cs_main, pwallet->cs_wallet);
        if (!pwallet->SignAndSubmitTransaction(reservekey, witnessTransaction, reasonForFail, &finalTransactionHash))
        {
            throw witness_error(witness::RPC_MISC_ERROR, strprintf("Failed to commit transaction [%s]", reasonForFail.c_str()));
        }
    }

    // Set result parameters
    if (pTxid != nullptr)
        *pTxid = finalTransactionHash.GetHex();
    if (pFee != nullptr)
        *pFee = transactionFee;
}

void redistributewitnessaccount(CWallet* pwallet, CAccount* fundingAccount, CAccount* witnessAccount, const std::vector<CAmount>& redistributionAmounts, std::string* pTxid, CAmount* pFee)
{
    redistributeandextendwitnessaccount(pwallet, fundingAccount, witnessAccount, redistributionAmounts, 0, pTxid, pFee);
}

void extendwitnessaccount(CWallet* pwallet, CAccount* fundingAccount, CAccount* witnessAccount, CAmount amount, uint64_t requestedLockPeriodInBlocks, std::string* pTxid, CAmount* pFee)
{
    CGetWitnessInfo witnessInfo = GetWitnessInfoWrapper();
    auto distribution = optimalWitnessDistribution(amount, requestedLockPeriodInBlocks, witnessInfo.nTotalWeightEligibleRaw);
    redistributeandextendwitnessaccount(pwallet, fundingAccount, witnessAccount, distribution, requestedLockPeriodInBlocks, pTxid, pFee);
}

uint64_t adjustedWeightForAmount(const CAmount amount, const uint64_t nHeight, const uint64_t duration, uint64_t networkWeight)
{
    uint64_t maxWeight = networkWeight / 100;
    uint64_t rawWeight = GetPoW2RawWeightForAmount(amount, nHeight, duration);
    uint64_t weight = std::min(rawWeight, maxWeight);
    return weight;
}

/** Estimated witnessing count expressed as a fraction per block for a single amount */
double witnessFraction(const CAmount amount, const uint64_t nHeight, const uint64_t duration, const uint64_t totalWeight)
{
    uint64_t weight = adjustedWeightForAmount(amount, nHeight, duration, totalWeight);

    // election probability
    const double p = double(weight) / totalWeight;

    // adjust for cooldown
    double fraction = 1.0 / (gMinimumParticipationAge + 1.0/p);

    return fraction;
}

/** Estimated witnessing count expressed as a fraction per block for an amount distribution */
double witnessFraction(const std::vector<CAmount>& amounts, const uint64_t nHeight, const uint64_t duration, const uint64_t totalWeight)
{
    double fraction = std::accumulate(amounts.begin(), amounts.end(), 0.0, [=](double acc, CAmount amount) {
        return acc + witnessFraction(amount, nHeight, duration, totalWeight);
    });
    return fraction;
}

std::tuple<std::vector<CAmount>, uint64_t, CAmount> witnessDistribution(CWallet* pWallet, CAccount* account)
{
    // assumes all account witness outputs have identical characteristics

    LOCK2(cs_main, pWallet->cs_wallet);

    const auto unspentWitnessOutputs = getCurrentOutputsForWitnessAccount(account);

    std::vector<CAmount> distribution;
    std::transform(unspentWitnessOutputs.begin(), unspentWitnessOutputs.end(), std::back_inserter(distribution), [](const auto& it) {
        const CTxOut& txOut = std::get<0>(it);
        return txOut.nValue;
    });

    CAmount total = std::accumulate(unspentWitnessOutputs.begin(), unspentWitnessOutputs.end(), CAmount(0), [](const CAmount acc, const auto& it){
        const CTxOut& txOut = std::get<0>(it);
        return acc + txOut.nValue;
    });

    int64_t duration = 0;
    if (unspentWitnessOutputs.size() > 0) {
        const CTxOut& txOut = std::get<0>(unspentWitnessOutputs[0]);
        uint64_t nUnused1, nUnused2;
        duration = GetPoW2LockLengthInBlocksFromOutput(txOut, std::get<1>(unspentWitnessOutputs[0]), nUnused1, nUnused2);
    }

    return std::tuple(distribution, duration, total);
}

CAmount maxAmountForDurationAndWeight(uint64_t lockDuration, uint64_t nHeight, uint64_t targetWeight)
{
    (unused) nHeight;
    // note that yearly_blocks is only correct for mainnet and should be parametrized for testnet, however it is consistent with
    // with other parts of the code that also use mainnet characteristics for weight determination when on testnet
    const double yearly_blocks = 365 * gRefactorDailyBlocksUsage;
    const double K = 100000.0;
    const double T = (1.0 + lockDuration / (yearly_blocks));

    // solve quadratic to find amount that will match weight
    const double A = T / K;
    const double B = T;
    const double C = - (double)(targetWeight);

    double amount = (-B + sqrt(B*B - 4.0 * A * C)) / (2.0 * A);

    return CAmount (amount * COIN);
}

std::vector<CAmount> optimalWitnessDistribution(CAmount totalAmount, uint64_t duration, uint64_t totalWeight)
{
    std::vector<CAmount> distribution;

    // Amount where maximum weight is reached and so any extra on top of that will not produce any gains
    CAmount partMax = maxAmountForDurationAndWeight(duration, chainActive.Height(), totalWeight/100);
    // Amount we have to be above to be a valid part of chain
    CAmount partMin = maxAmountForDurationAndWeight(duration, chainActive.Height(), gMinimumWitnessWeight)+1;
    if (partMin < gMinimumWitnessAmount*COIN)
        partMin = gMinimumWitnessAmount*COIN+1;

    // Divide int parts into 96% of maximum workable amount.
    // Leaves some room for:
    // a) leaves some room for entwork weight fluctuatiopns
    // b) leaves some room when total network witness weight changes
    CAmount partTarget = (96 * partMax) / 100;

    // Don't divide at all if parts are smaller than this
    CAmount partTargetMin = (60 * partMax) / 100;

    // ensure minimum criterium is met (on mainnet this is not expected to happen)
    if (partTarget < partMin)
        partTarget = partMin;

    int wholeParts = totalAmount / partTarget;

    if (wholeParts > 1)
    {
        CAmount remainder = totalAmount - wholeParts * partTarget;
        CAmount partRemainder = remainder/wholeParts;

        for (int i=0; i< wholeParts; i++)
        {
            distribution.push_back(partTarget+partRemainder);
            remainder -= partRemainder;
        }

        // add any final remainder to first part
        distribution[0] += remainder;
    }
    else if (wholeParts == 1 && (totalAmount > partTarget) && (totalAmount / 2 > partTargetMin))
    {
        CAmount remainder = totalAmount - (totalAmount/2*2);
        distribution.push_back((totalAmount/2)+remainder);
        distribution.push_back(totalAmount/2);
    }
    else
    {
        distribution.push_back(totalAmount);
    }
    return distribution;
}

bool isWitnessDistributionNearOptimal(CWallet* pWallet, CAccount* account, const CGetWitnessInfo& witnessInfo)
{
    // NB! We prefer the raw weight to the eligible weight as the raw weight fluctuates less
    // And over time the two should become close anyway
    uint64_t totalWeight = witnessInfo.nTotalWeightEligibleRaw;

    auto [currentDistribution, duration, totalAmount] = witnessDistribution(pWallet, account);
    double currentFraction = witnessFraction(currentDistribution, chainActive.Height(), duration, totalWeight);

    auto optimalDistribution = optimalWitnessDistribution(totalAmount, duration, totalWeight);
    double optimalFraction = witnessFraction(optimalDistribution, chainActive.Height(), duration, totalWeight);

    const double OPTIMAL_DISTRIBUTION_THRESHOLD = 0.95;
    bool nearOptimal = currentFraction / optimalFraction >= OPTIMAL_DISTRIBUTION_THRESHOLD;
    return nearOptimal;
}

uint64_t combinedWeight(const std::vector<CAmount> amounts, uint64_t height, uint64_t duration)
{
    return std::accumulate(amounts.begin(), amounts.end(), uint64_t(0), [=](uint64_t acc, CAmount amount)
    {
        return acc + GetPoW2RawWeightForAmount(amount, height, duration);
    });
}

std::string witnessKeysLinkUrlForAccount(CWallet* pWallet, CAccount* account)
{
    std::set<CKeyID> keys;

    LOCK2(cs_main, pWallet->cs_wallet);

    if (chainActive.Tip())
    {
        std::map<COutPoint, Coin> allWitnessCoins;
        if (getAllUnspentWitnessCoins(chainActive, Params(), chainActive.Tip(), allWitnessCoins))
        {
            for (const auto& [witnessOutPoint, witnessCoin] : allWitnessCoins)
            {
                (unused)witnessOutPoint;
                CTxOutPoW2Witness witnessDetails;
                GetPow2WitnessOutput(witnessCoin.out, witnessDetails);
                if (account->HaveKey(witnessDetails.witnessKeyID))
                {
                    keys.insert(witnessDetails.witnessKeyID);
                }
            }
        }
    }

    std::string witnessAccountKeys = "";
    for (const CKeyID& key: keys) {
        //fixme: (FUT) - to be 100% correct we should export the creation time of the actual key (where available) and not getEarliestPossibleCreationTime - however getEarliestPossibleCreationTime will do for now.
        CKey witnessPrivKey;
        if (account->GetKey(key, witnessPrivKey))
        witnessAccountKeys += CEncodedSecretKey(witnessPrivKey).ToString() + strprintf("#%s", account->getEarliestPossibleCreationTime());
        witnessAccountKeys += ":";
    }

    if (!witnessAccountKeys.empty())
    {
        witnessAccountKeys.pop_back();
        witnessAccountKeys = GLOBAL_APP_URIPREFIX"://witnesskeys?keys=" + witnessAccountKeys;
    }

    return witnessAccountKeys;
}


text:
using namespace clang::ast_matchers;

namespace clang {
namespace tidy {
namespace abseil {

void DurationAdditionCheck::registerMatchers(MatchFinder *Finder) {
  Finder->addMatcher(
      binaryOperator(hasOperatorName("+"),
                     hasEitherOperand(expr(ignoringParenImpCasts(
                         callExpr(callee(functionDecl(TimeConversionFunction())
                                             .bind("function_decl")))
                             .bind("call")))))
          .bind("binop"),
      this);
}

void DurationAdditionCheck::check(const MatchFinder::MatchResult &Result) {
  const BinaryOperator *Binop =
      Result.Nodes.getNodeAs<clang::BinaryOperator>("binop");
  const CallExpr *Call = Result.Nodes.getNodeAs<clang::CallExpr>("call");

  // Don't try to replace things inside of macro definitions.
  if (Binop->getExprLoc().isMacroID() || Binop->getExprLoc().isInvalid())
    return;

  llvm::Optional<DurationScale> Scale = getScaleForTimeInverse(
      Result.Nodes.getNodeAs<clang::FunctionDecl>("function_decl")->getName());
  if (!Scale)
    return;

  llvm::StringRef TimeFactory = getTimeInverseForScale(*Scale);

  FixItHint Hint;
  if (Call == Binop->getLHS()->IgnoreParenImpCasts()) {
    Hint = FixItHint::CreateReplacement(
        Binop->getSourceRange(),
        (llvm::Twine(TimeFactory) + "(" +
         tooling::fixit::getText(*Call->getArg(0), *Result.Context) + " + " +
         rewriteExprFromNumberToDuration(Result, *Scale, Binop->getRHS()) + ")")
            .str());
  } else {
    assert(Call == Binop->getRHS()->IgnoreParenImpCasts() &&
           "Call should be found on the RHS");
    Hint = FixItHint::CreateReplacement(
        Binop->getSourceRange(),
        (llvm::Twine(TimeFactory) + "(" +
         rewriteExprFromNumberToDuration(Result, *Scale, Binop->getLHS()) +
         " + " + tooling::fixit::getText(*Call->getArg(0), *Result.Context) +
         ")")
            .str());
  }

  diag(Binop->getBeginLoc(), "perform addition in the duration domain") << Hint;
}

} // namespace abseil
} // namespace tidy
} // namespace clang


text:
package com.quadbits.gdxhelper.controllers;

import com.badlogic.gdx.scenes.scene2d.Actor;

/**
 *
 */
public interface NonContinuousRenderingController {
    /**
     * Calculates the maximum time that a game could sleep without redrawing in order to
     * prevent visible changes in the actor to be too abrupt.
     *
     * @return the max. sleep time, in milliseconds
     */

    /**
     * @param actor
     *
     * @return
     */
    public long getMaxSleepTime(Actor actor);
}


text:
package org.jasig.cas.ticket.registry;

import org.jasig.cas.ticket.ServiceTicket;
import org.jasig.cas.ticket.TicketGrantingTicket;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Test case to test the DefaultTicketRegistry based on test cases to test all
 * Ticket Registries.
 *
 * @author Cyrille Le Clerc
 */
public final class EhCacheTicketRegistryTests extends AbstractTicketRegistryTests {

    private ClassPathXmlApplicationContext applicationContext;

    public EhCacheTicketRegistryTests() {
        applicationContext = new ClassPathXmlApplicationContext("classpath:ticketRegistry.xml");
    }

    @Override
    public TicketRegistry getNewTicketRegistry() throws Exception {
        return (TicketRegistry) applicationContext.getBean("ticketRegistry");
    }

    /**
     * Disabled because {@link EhCacheTicketRegistry#getTickets()} returns an
     * {@link UnsupportedOperationException}
     */
    @Override
    public void testGetTicketsIsZero() {
    }

    /**
     * Disabled because {@link EhCacheTicketRegistry#getTickets()} returns an
     * {@link UnsupportedOperationException}
     */
    @Override
    public void testGetTicketsFromRegistryEqualToTicketsAdded() {
    }

}


text:
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;

/// <summary>
/// Inspector class used to view and edit UIFonts.
/// </summary>

[CustomEditor(typeof(UIFont))]
public class UIFontInspector : Editor
{
	enum View
	{
		Nothing,
		Atlas,
		Font,
	}

	enum FontType
	{
		Bitmap,
		Reference,
		Dynamic,
	}

	static View mView = View.Font;
	static bool mUseShader = false;

	UIFont mFont;
	FontType mType = FontType.Bitmap;
	UIFont mReplacement = null;
	string mSymbolSequence = "";
	string mSymbolSprite = "";
	BMSymbol mSelectedSymbol = null;
	AnimationCurve mCurve = new AnimationCurve(new Keyframe(0f, 0f), new Keyframe(1f, 1f));

	public override bool HasPreviewGUI () { return mView != View.Nothing; }

	void OnSelectFont (Object obj)
	{
		// Undo doesn't work correctly in this case... so I won't bother.
		//NGUIEditorTools.RegisterUndo("Font Change");
		//NGUIEditorTools.RegisterUndo("Font Change", mFont);

		mFont.replacement = obj as UIFont;
		mReplacement = mFont.replacement;
		NGUITools.SetDirty(mFont);
	}

	void OnSelectAtlas (Object obj)
	{
		if (mFont != null && mFont.atlas != obj)
		{
			NGUIEditorTools.RegisterUndo("Font Atlas", mFont);
			mFont.atlas = obj as UIAtlas;
			MarkAsChanged();
		}
	}

	void MarkAsChanged ()
	{
		List<UILabel> labels = NGUIEditorTools.FindAll<UILabel>();

		foreach (UILabel lbl in labels)
		{
			if (UIFont.CheckIfRelated(lbl.bitmapFont, mFont))
			{
				lbl.bitmapFont = null;
				lbl.bitmapFont = mFont;
			}
		}
	}

	public override void OnInspectorGUI ()
	{
		mFont = target as UIFont;
		NGUIEditorTools.SetLabelWidth(80f);

		GUILayout.Space(6f);

		if (mFont.replacement != null)
		{
			mType = FontType.Reference;
			mReplacement = mFont.replacement;
		}
		else if (mFont.dynamicFont != null)
		{
			mType = FontType.Dynamic;
		}

		GUI.changed = false;
		GUILayout.BeginHorizontal();
		mType = (FontType)EditorGUILayout.EnumPopup("Font Type", mType);
		GUILayout.Space(18f);
		GUILayout.EndHorizontal();

		if (GUI.changed)
		{
			if (mType == FontType.Bitmap)
				OnSelectFont(null);

			if (mType != FontType.Dynamic && mFont.dynamicFont != null)
				mFont.dynamicFont = null;
		}

		if (mType == FontType.Reference)
		{
			ComponentSelector.Draw<UIFont>(mFont.replacement, OnSelectFont, true);

			GUILayout.Space(6f);
			EditorGUILayout.HelpBox("You can have one font simply point to " +
				"another one. This is useful if you want to be " +
				"able to quickly replace the contents of one " +
				"font with another one, for example for " +
				"swapping an SD font with an HD one, or " +
				"replacing an English font with a Chinese " +
				"one. All the labels referencing this font " +
				"will update their references to the new one.", MessageType.Info);

			if (mReplacement != mFont && mFont.replacement != mReplacement)
			{
				NGUIEditorTools.RegisterUndo("Font Change", mFont);
				mFont.replacement = mReplacement;
				NGUITools.SetDirty(mFont);
			}
			return;
		}
		else if (mType == FontType.Dynamic)
		{
#if UNITY_3_5
			EditorGUILayout.HelpBox("Dynamic fonts require Unity 4.0 or higher.", MessageType.Error);
#else
			Font fnt = EditorGUILayout.ObjectField("TTF Font", mFont.dynamicFont, typeof(Font), false) as Font;

			if (fnt != mFont.dynamicFont)
			{
				NGUIEditorTools.RegisterUndo("Font change", mFont);
				mFont.dynamicFont = fnt;
			}

			Material mat = EditorGUILayout.ObjectField("Material", mFont.material, typeof(Material), false) as Material;

			if (mFont.material != mat)
			{
				NGUIEditorTools.RegisterUndo("Font Material", mFont);
				mFont.material = mat;
			}

			GUILayout.BeginHorizontal();
			int size = EditorGUILayout.IntField("Default Size", mFont.defaultSize, GUILayout.Width(120f));
			FontStyle style = (FontStyle)EditorGUILayout.EnumPopup(mFont.dynamicFontStyle);
			GUILayout.Space(18f);
			GUILayout.EndHorizontal();

			if (size != mFont.defaultSize)
			{
				NGUIEditorTools.RegisterUndo("Font change", mFont);
				mFont.defaultSize = size;
			}

			if (style != mFont.dynamicFontStyle)
			{
				NGUIEditorTools.RegisterUndo("Font change", mFont);
				mFont.dynamicFontStyle = style;
			}
#endif
		}
		else
		{
			ComponentSelector.Draw<UIAtlas>(mFont.atlas, OnSelectAtlas, true);

			if (mFont.atlas != null)
			{
				if (mFont.bmFont.isValid)
				{
					NGUIEditorTools.DrawAdvancedSpriteField(mFont.atlas, mFont.spriteName, SelectSprite, false);
				}
				EditorGUILayout.Space();
			}
			else
			{
				// No atlas specified -- set the material and texture rectangle directly
				Material mat = EditorGUILayout.ObjectField("Material", mFont.material, typeof(Material), false) as Material;

				if (mFont.material != mat)
				{
					NGUIEditorTools.RegisterUndo("Font Material", mFont);
					mFont.material = mat;
				}
			}

			// For updating the font's data when importing from an external source, such as the texture packer
			bool resetWidthHeight = false;

			if (mFont.atlas != null || mFont.material != null)
			{
				TextAsset data = EditorGUILayout.ObjectField("Import Data", null, typeof(TextAsset), false) as TextAsset;

				if (data != null)
				{
					NGUIEditorTools.RegisterUndo("Import Font Data", mFont);
					BMFontReader.Load(mFont.bmFont, NGUITools.GetHierarchy(mFont.gameObject), data.bytes);
					mFont.MarkAsChanged();
					resetWidthHeight = true;
					Debug.Log("Imported " + mFont.bmFont.glyphCount + " characters");
				}
			}

			if (mFont.bmFont.isValid)
			{
				Texture2D tex = mFont.texture;

				if (tex != null && mFont.atlas == null)
				{
					// Pixels are easier to work with than UVs
					Rect pixels = NGUIMath.ConvertToPixels(mFont.uvRect, tex.width, tex.height, false);

					// Automatically set the width and height of the rectangle to be the original font texture's dimensions
					if (resetWidthHeight)
					{
						pixels.width = mFont.texWidth;
						pixels.height = mFont.texHeight;
					}

					// Font sprite rectangle
					pixels = EditorGUILayout.RectField("Pixel Rect", pixels);

					// Convert the pixel coordinates back to UV coordinates
					Rect uvRect = NGUIMath.ConvertToTexCoords(pixels, tex.width, tex.height);

					if (mFont.uvRect != uvRect)
					{
						NGUIEditorTools.RegisterUndo("Font Pixel Rect", mFont);
						mFont.uvRect = uvRect;
					}
					//NGUIEditorTools.DrawSeparator();
					EditorGUILayout.Space();
				}
			}
		}

		// Dynamic fonts don't support emoticons
		if (!mFont.isDynamic && mFont.bmFont.isValid)
		{
			if (mFont.atlas != null)
			{
				if (NGUIEditorTools.DrawHeader("Symbols and Emoticons"))
				{
					NGUIEditorTools.BeginContents();

					List<BMSymbol> symbols = mFont.symbols;

					for (int i = 0; i < symbols.Count; )
					{
						BMSymbol sym = symbols[i];

						GUILayout.BeginHorizontal();
						GUILayout.Label(sym.sequence, GUILayout.Width(40f));
						if (NGUIEditorTools.DrawSpriteField(mFont.atlas, sym.spriteName, ChangeSymbolSprite, GUILayout.MinWidth(100f)))
							mSelectedSymbol = sym;

						if (GUILayout.Button("Edit", GUILayout.Width(40f)))
						{
							if (mFont.atlas != null)
							{
								NGUISettings.atlas = mFont.atlas;
								NGUISettings.selectedSprite = sym.spriteName;
								NGUIEditorTools.Select(mFont.atlas.gameObject);
							}
						}

						GUI.backgroundColor = Color.red;

						if (GUILayout.Button("X", GUILayout.Width(22f)))
						{
							NGUIEditorTools.RegisterUndo("Remove symbol", mFont);
							mSymbolSequence = sym.sequence;
							mSymbolSprite = sym.spriteName;
							symbols.Remove(sym);
							mFont.MarkAsChanged();
						}
						GUI.backgroundColor = Color.white;
						GUILayout.EndHorizontal();
						GUILayout.Space(4f);
						++i;
					}

					if (symbols.Count > 0)
					{
						GUILayout.Space(6f);
					}

					GUILayout.BeginHorizontal();
					mSymbolSequence = EditorGUILayout.TextField(mSymbolSequence, GUILayout.Width(40f));
					NGUIEditorTools.DrawSpriteField(mFont.atlas, mSymbolSprite, SelectSymbolSprite);

					bool isValid = !string.IsNullOrEmpty(mSymbolSequence) && !string.IsNullOrEmpty(mSymbolSprite);
					GUI.backgroundColor = isValid ? Color.green : Color.grey;

					if (GUILayout.Button("Add", GUILayout.Width(40f)) && isValid)
					{
						NGUIEditorTools.RegisterUndo("Add symbol", mFont);
						mFont.AddSymbol(mSymbolSequence, mSymbolSprite);
						mFont.MarkAsChanged();
						mSymbolSequence = "";
						mSymbolSprite = "";
					}
					GUI.backgroundColor = Color.white;
					GUILayout.EndHorizontal();

					if (symbols.Count == 0)
					{
						EditorGUILayout.HelpBox("Want to add an emoticon to your font? In the field above type ':)', choose a sprite, then hit the Add button.", MessageType.Info);
					}
					else GUILayout.Space(4f);

					NGUIEditorTools.EndContents();
				}
			}
		}

		if (mFont.bmFont != null && mFont.bmFont.isValid)
		{
			if (NGUIEditorTools.DrawHeader("Modify"))
			{
				NGUIEditorTools.BeginContents();

				UISpriteData sd = mFont.sprite;

				bool disable = (sd != null && (sd.paddingLeft != 0 || sd.paddingBottom != 0));
				EditorGUI.BeginDisabledGroup(disable || mFont.packedFontShader);

				EditorGUILayout.BeginHorizontal();
				GUILayout.Space(20f);
				EditorGUILayout.BeginVertical();

				GUILayout.BeginHorizontal();
				GUILayout.BeginVertical();
				NGUISettings.foregroundColor = EditorGUILayout.ColorField("Foreground", NGUISettings.foregroundColor);
				NGUISettings.backgroundColor = EditorGUILayout.ColorField("Background", NGUISettings.backgroundColor);
				GUILayout.EndVertical();
				mCurve = EditorGUILayout.CurveField("", mCurve, GUILayout.Width(40f), GUILayout.Height(40f));
				GUILayout.EndHorizontal();

				if (GUILayout.Button("Add a Shadow")) ApplyEffect(Effect.Shadow, NGUISettings.foregroundColor, NGUISettings.backgroundColor);
				if (GUILayout.Button("Add a Soft Outline")) ApplyEffect(Effect.Outline, NGUISettings.foregroundColor, NGUISettings.backgroundColor);
				if (GUILayout.Button("Rebalance Colors")) ApplyEffect(Effect.Rebalance, NGUISettings.foregroundColor, NGUISettings.backgroundColor);
				if (GUILayout.Button("Apply Curve to Alpha")) ApplyEffect(Effect.AlphaCurve, NGUISettings.foregroundColor, NGUISettings.backgroundColor);
				if (GUILayout.Button("Apply Curve to Foreground")) ApplyEffect(Effect.ForegroundCurve, NGUISettings.foregroundColor, NGUISettings.backgroundColor);
				if (GUILayout.Button("Apply Curve to Background")) ApplyEffect(Effect.BackgroundCurve, NGUISettings.foregroundColor, NGUISettings.backgroundColor);

				GUILayout.Space(10f);
				if (GUILayout.Button("Add Transparent Border (+1)")) ApplyEffect(Effect.Border, NGUISettings.foregroundColor, NGUISettings.backgroundColor);
				if (GUILayout.Button("Remove Border (-1)")) ApplyEffect(Effect.Crop, NGUISettings.foregroundColor, NGUISettings.backgroundColor);

				EditorGUILayout.EndVertical();
				GUILayout.Space(20f);
				EditorGUILayout.EndHorizontal();

				EditorGUI.EndDisabledGroup();

				if (disable)
				{
					GUILayout.Space(3f);
					EditorGUILayout.HelpBox("The sprite used by this font has been trimmed and is not suitable for modification. " +
						"Try re-adding this sprite with 'Trim Alpha' disabled.", MessageType.Warning);
				}

				NGUIEditorTools.EndContents();
			}
		}

		// The font must be valid at this point for the rest of the options to show up
		if (mFont.isDynamic || mFont.bmFont.isValid)
		{
			if (mFont.atlas == null)
			{
				mView = View.Font;
				mUseShader = false;
			}
		}

		// Preview option
		if (!mFont.isDynamic && mFont.atlas != null)
		{
			GUILayout.BeginHorizontal();
			{
				mView = (View)EditorGUILayout.EnumPopup("Preview", mView);
				GUILayout.Label("Shader", GUILayout.Width(45f));
				mUseShader = EditorGUILayout.Toggle(mUseShader, GUILayout.Width(20f));
			}
			GUILayout.EndHorizontal();
		}
	}

	/// <summary>
	/// "New Sprite" selection.
	/// </summary>

	void SelectSymbolSprite (string spriteName)
	{
		mSymbolSprite = spriteName;
		Repaint();
	}

	/// <summary>
	/// Existing sprite selection.
	/// </summary>

	void ChangeSymbolSprite (string spriteName)
	{
		if (mSelectedSymbol != null && mFont != null)
		{
			NGUIEditorTools.RegisterUndo("Change symbol", mFont);
			mSelectedSymbol.spriteName = spriteName;
			Repaint();
			mFont.MarkAsChanged();
		}
	}

	/// <summary>
	/// Draw the font preview window.
	/// </summary>

	public override void OnPreviewGUI (Rect rect, GUIStyle background)
	{
		mFont = target as UIFont;
		if (mFont == null) return;
		Texture2D tex = mFont.texture;

		if (mView != View.Nothing && tex != null)
		{
			Material m = (mUseShader ? mFont.material : null);

			if (mView == View.Font && mFont.atlas != null && mFont.sprite != null)
			{
				NGUIEditorTools.DrawSprite(tex, rect, mFont.sprite, Color.white, m);
			}
			else
			{
				NGUIEditorTools.DrawTexture(tex, rect, new Rect(0f, 0f, 1f, 1f), Color.white, m);
			}
		}
	}

	/// <summary>
	/// Sprite selection callback.
	/// </summary>

	void SelectSprite (string spriteName)
	{
		NGUIEditorTools.RegisterUndo("Font Sprite", mFont);
		mFont.spriteName = spriteName;
		Repaint();
	}

	enum Effect
	{
		Rebalance,
		ForegroundCurve,
		BackgroundCurve,
		AlphaCurve,
		Border,
		Shadow,
		Outline,
		Crop,
	}

	/// <summary>
	/// Apply an effect to the font.
	/// </summary>

	void ApplyEffect (Effect effect, Color foreground, Color background)
	{
		BMFont bf = mFont.bmFont;
		int offsetX = 0;
		int offsetY = 0;

		if (mFont.atlas != null)
		{
			UISpriteData sd = mFont.atlas.GetSprite(bf.spriteName);
			if (sd == null) return;
			offsetX = sd.x;
			offsetY = sd.y + mFont.texHeight - sd.paddingTop;
		}

		string path = AssetDatabase.GetAssetPath(mFont.texture);
		Texture2D bfTex = NGUIEditorTools.ImportTexture(path, true, true, false);
		Color32[] atlas = bfTex.GetPixels32();

		// First we need to extract textures for all the glyphs, making them bigger in the process
		List<BMGlyph> glyphs = bf.glyphs;
		List<Texture2D> glyphTextures = new List<Texture2D>(glyphs.Count);

		for (int i = 0, imax = glyphs.Count; i < imax; ++i)
		{
			BMGlyph glyph = glyphs[i];
			if (glyph.width < 1 || glyph.height < 1) continue;

			int width = glyph.width;
			int height = glyph.height;

			if (effect == Effect.Outline || effect == Effect.Shadow || effect == Effect.Border)
			{
				width += 2;
				height += 2;
				--glyph.offsetX;
				--glyph.offsetY;
			}
			else if (effect == Effect.Crop && width > 2 && height > 2)
			{
				width -= 2;
				height -= 2;
				++glyph.offsetX;
				++glyph.offsetY;
			}

			int size = width * height;
			Color32[] colors = new Color32[size];
			Color32 clear = background;
			clear.a = 0;
			for (int b = 0; b < size; ++b) colors[b] = clear;

			if (effect == Effect.Crop)
			{
				for (int y = 0; y < height; ++y)
				{
					for (int x = 0; x < width; ++x)
					{
						int fx = x + glyph.x + offsetX + 1;
						int fy = y + (mFont.texHeight - glyph.y - glyph.height) + 1;
						if (mFont.atlas != null) fy += bfTex.height - offsetY;
						colors[x + y * width] = atlas[fx + fy * bfTex.width];
					}
				}
			}
			else
			{
				for (int y = 0; y < glyph.height; ++y)
				{
					for (int x = 0; x < glyph.width; ++x)
					{
						int fx = x + glyph.x + offsetX;
						int fy = y + (mFont.texHeight - glyph.y - glyph.height);
						if (mFont.atlas != null) fy += bfTex.height - offsetY;

						Color c = atlas[fx + fy * bfTex.width];

						if (effect == Effect.Border)
						{
							colors[x + 1 + (y + 1) * width] = c;
						}
						else
						{
							if (effect == Effect.AlphaCurve) c.a = Mathf.Clamp01(mCurve.Evaluate(c.a));

							Color bg = background;
							bg.a = (effect == Effect.BackgroundCurve) ? Mathf.Clamp01(mCurve.Evaluate(c.a)) : c.a;

							Color fg = foreground;
							fg.a = (effect == Effect.ForegroundCurve) ? Mathf.Clamp01(mCurve.Evaluate(c.a)) : c.a;

							if (effect == Effect.Outline || effect == Effect.Shadow)
							{
								colors[x + 1 + (y + 1) * width] = Color.Lerp(bg, c, c.a);
							}
							else
							{
								colors[x + y * width] = Color.Lerp(bg, fg, c.a);
							}
						}
					}
				}

				// Apply the appropriate affect
				if (effect == Effect.Shadow) NGUIEditorTools.AddShadow(colors, width, height, NGUISettings.backgroundColor);
				else if (effect == Effect.Outline) NGUIEditorTools.AddDepth(colors, width, height, NGUISettings.backgroundColor);
			}

			Texture2D tex = new Texture2D(width, height, TextureFormat.ARGB32, false);
			tex.SetPixels32(colors);
			tex.Apply();
			glyphTextures.Add(tex);
		}

		// Pack all glyphs into a new texture
		Texture2D final = new Texture2D(bfTex.width, bfTex.height, TextureFormat.ARGB32, false);
		Rect[] rects = final.PackTextures(glyphTextures.ToArray(), 1);
		final.Apply();

		// Make RGB channel use the background color (Unity makes it black by default)
		Color32[] fcs = final.GetPixels32();
		Color32 bc = background;

		for (int i = 0, imax = fcs.Length; i < imax; ++i)
		{
			if (fcs[i].a == 0)
			{
				fcs[i].r = bc.r;
				fcs[i].g = bc.g;
				fcs[i].b = bc.b;
			}
		}

		final.SetPixels32(fcs);
		final.Apply();

		// Update the glyph rectangles
		int index = 0;
		int tw = final.width;
		int th = final.height;

		for (int i = 0, imax = glyphs.Count; i < imax; ++i)
		{
			BMGlyph glyph = glyphs[i];
			if (glyph.width < 1 || glyph.height < 1) continue;

			Rect rect = rects[index++];
			glyph.x = Mathf.RoundToInt(rect.x * tw);
			glyph.y = Mathf.RoundToInt(rect.y * th);
			glyph.width = Mathf.RoundToInt(rect.width * tw);
			glyph.height = Mathf.RoundToInt(rect.height * th);
			glyph.y = th - glyph.y - glyph.height;
		}

		// Update the font's texture dimensions
		mFont.texWidth = final.width;
		mFont.texHeight = final.height;

		if (mFont.atlas == null)
		{
			// Save the final texture
			byte[] bytes = final.EncodeToPNG();
			NGUITools.DestroyImmediate(final);
			System.IO.File.WriteAllBytes(path, bytes);
			AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);
		}
		else
		{
			// Update the atlas
			final.name = mFont.spriteName;
			bool val = NGUISettings.atlasTrimming;
			NGUISettings.atlasTrimming = false;
			UIAtlasMaker.AddOrUpdate(mFont.atlas, final);
			NGUISettings.atlasTrimming = val;
			NGUITools.DestroyImmediate(final);
		}

		// Cleanup
		for (int i = 0; i < glyphTextures.Count; ++i)
			NGUITools.DestroyImmediate(glyphTextures[i]);

		// Refresh all labels
		mFont.MarkAsChanged();
	}
}


text:
<TITLE>Review for Life and Times of Hank Greenberg, The (1998)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Life and Times of Hank Greenberg, The (1998)

reviewed by
Harvey S. Karten

THE LIFE AND TIMES OF HANK GREENBERG

 Reviewed by Harvey Karten
 Cowboy Booking International/Ciesla Foundation
 Director: Aviva Kempner
 Writer: Aviva Kempner
 Cast: Hank Greenberg, Ira Berkow, Bob Feller, Dick Schaap,
Alan Dershowitz, Walter Matthau
 Theater: Premiere at Film Forum 209 W. Houston S5. New
York NY Jan. 12-25, 2000

    Those of us who think that there's something sinister,
something wrong about the political correctness movement
might have a change of mind after seeing "The Life and
Times of Hank Greenberg."  This documentary about one of
the greatest Jewish ballplayers of the century illustrates the
hatred allowed to come out of the mouths of some
degenerate Americans, Americans who somehow thought
that if a person is not a white Christian, he has no business
playing in a game that was "meant for them."  Happily the PC
movement may not have changed everyone's mind about
racial and religious minorities, but at least unhealthy slurs are
not in fashion, at least in public, as they seem to have been
during the era that saw Greenberg challenge Babe Ruth's
record of homers.  Greenberg was a player for the Detroit
Tigers from 1933-1946 before he was traded by them to the
Pirates for whom he played an additional season.  Aviva
Kempner's congenial and often rousing and humorous
documentary gives us access to some archival footage of
Greenberg both at bat and on first base and in left field.  But
her focus is foremost on the fact that Hank Greenberg was
the first Jewish baseball player who, though completely
secular, never hid his religion despite its unpopularity with the
bigots of this country.  (He was not the first Jewish ballplayer
in the Majors: a few, not named here, preceded him, but they
had apparently changed their names to pass for Christian.)

   Punctuating the documentary with Henry Sapoznik's
Klezmer-infused score, director Kempner--whose previous
work was as co-scripter and producer of "Partisans of Vilna"
(about Jewish resistance against the Nazis)--succeeds in this
12-year-long labor of love to give us a grand look at the
handsome but gawky, 6'4" athlete who served as an icon for
Jews throughout the country.  Setting her footage of pennant-
winning and series-winning baseball games against interviews
with forty-odd fans, family and celebrities, she gives us a
rounded picture of the largely anti-Semitic spirit of the times,
a spirit which led to Greenberg's being greeted by hate-filled
catcalls from the stands and in one instance even from the
bench of an opposing team.  Young people today would be
aghast to see samples of help-wanted pages from the thirties
advertising for "Christians Only" and "Must be of Anglo-Saxon
descent--as such proclamations are not only illegal today but
would be laughable outside circles like KKK, the American
Nazi party and so-called white citizens' councils.  Yet during
the 1930s a figure as illustrious as Henry Ford would publish
a book called "The International Jew" (how those of the
Jewish persuasion were corrupting capitalism and furthering
communism).

   Documentaries are not very popular in America, the
principal reason being perhaps the fear that they are little
more than opportunities for talking heads.  Talking heads do
indeed populate the film, but those captured by Thomas
Kaufman's camera are an amusing lot, including Walter
Matthau and Alan Dershowitz.  Though not alluded to in the
film, Dershowitz, one of the country's foremost attorneys, had
written a book called "Chutzpah," in which he challenges
Jews to be proud of their heritage and do nothing to hide
their ethnic identity.  In the interview, he explains that during
the thirties and forties, Jews were supposed to be quiet, or as
they say in Yiddish "shta, shtill." Jews were damned if they
failed and damned if they succeeded, so the common wisdom
was "Don't make waves."  Greenberg becomes, therefore,
one of Dershowitz's heroes, particularly when in deference to
his heritage and out of respect for his parents, he refused to
play ball on Yom Kippur despite turning in an impressive
performance on the preceding Rosh Hashanah.  (In the
movie's most engaging note, we learn that Greenberg's rabbi,
citing the Talmud, allowed Greenberg to ply his trade on the
Jewish New Year because "children in ancient times played
sporting games in the streets of Jerusalem."  What the rabbi
deliberately hid from the ball player's ears was that those
were Roman kids, not Jewish youngsters).

   Detractors of Hank Greenberg include a cop, photographed
when giving the player a ticket for going through an amber
light and saying "Who in hell ever heard of a Greenberg
being a ball player?"  Yet another was his drill sergeant--
Greenberg took up arms in World War 2--who announced to
his men, "I don't want any Cohens or Goldbergs on my
team."  The athlete raised his hand and said, "My name is
Greenberg."  Looking at the muscular, 6'4" hero, the drill
sergeant mumbled, "I didn't say anything about Greenbergs."

   For lack of funding, Kempner persisted for 12 years to get
this film out to the public, making her, like Greenberg, a hero.
Framed by Mandy Patinkin's singing "Take Me Out to the Ball
Game" in Yiddish against a backdrop of Bronx kids during the
Depression throwing the horsehide around the local streets,
"The Life and Times of Hank Greenberg" is well deserving of
the Audience Award it garnered from those attending its
screening at a Hamptons Film Festival.

Not Rated.  Running Time: 95 minutes.  (C) 2000
Harvey Karten, film_critic@compuserve.com

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


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

<title>HostProvisioner</title>
<meta name="date" content="2014-04-05">
<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

org.deeplearning4j.aws.ec2.provision

Class HostProvisioner

java.lang.Object

org.deeplearning4j.aws.ec2.provision.HostProvisioner

All Implemented Interfaces:

com.jcraft.jsch.UserInfo

public class HostProvisioner
extends java.lang.Object
implements com.jcraft.jsch.UserInfo

Meant for uploading files to remote servers

Constructor Summary

Constructors

Constructor and Description

HostProvisioner(java.lang.String host)

Connects to port 22, user root, with no password

HostProvisioner(java.lang.String host,
               java.lang.String user)

Connects to port 22

HostProvisioner(java.lang.String host,
               java.lang.String user,
               java.lang.String password)

Connects to port 22

HostProvisioner(java.lang.String host,
               java.lang.String user,
               java.lang.String password,
               int port)

Method Summary

Methods

Modifier and Type
Method and Description

void
addKeyFile(java.lang.String keyFile)

java.lang.String
getPassphrase()

java.lang.String
getPassword()

boolean
promptPassphrase(java.lang.String arg0)

boolean
promptPassword(java.lang.String arg0)

boolean
promptYesNo(java.lang.String arg0)

void
runRemoteCommand(java.lang.String remoteCommand)

void
showMessage(java.lang.String arg0)

void
uploadAndRun(java.lang.String script,
            java.lang.String rootDir)

void
uploadForDeployment(java.lang.String from,
                   java.lang.String to)

Creates the directory for the file if necessary
 and uploads the file

Methods inherited from class java.lang.Object

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

Constructor Detail

HostProvisioner

public HostProvisioner(java.lang.String host,
               java.lang.String user,
               java.lang.String password,
               int port)

Parameters:

host - host to connect to (public facing dns)

user - the user to connect with (default root otherwise)

password - the password to use if any

port - the port to connect to(default 22)

HostProvisioner

public HostProvisioner(java.lang.String host,
               java.lang.String user,
               java.lang.String password)

Connects to port 22

Parameters:

host - host to connect to (public facing dns)

user - the user to connect with (default root otherwise)

password - the password to use if any

HostProvisioner

public HostProvisioner(java.lang.String host,
               java.lang.String user)

Connects to port 22

Parameters:

host - host to connect to (public facing dns)

user - the user to connect with (default root otherwise)

password - the password to use if any

HostProvisioner

public HostProvisioner(java.lang.String host)

Connects to port 22, user root, with no password

Parameters:

host - host to connect to (public facing dns)

Method Detail

uploadAndRun

public void uploadAndRun(java.lang.String script,
                java.lang.String rootDir)
                  throws java.lang.Exception

Throws:

java.lang.Exception

runRemoteCommand

public void runRemoteCommand(java.lang.String remoteCommand)
                      throws java.lang.Exception

Throws:

java.lang.Exception

uploadForDeployment

public void uploadForDeployment(java.lang.String from,
                       java.lang.String to)
                         throws java.lang.Exception

Creates the directory for the file if necessary
 and uploads the file

Parameters:

from - the directory to upload from

to - the destination directory on the remote server

Throws:

java.lang.Exception

addKeyFile

public void addKeyFile(java.lang.String keyFile)
                throws java.lang.Exception

Throws:

java.lang.Exception

getPassphrase

public java.lang.String getPassphrase()

Specified by:

getPassphrase in interface com.jcraft.jsch.UserInfo

getPassword

public java.lang.String getPassword()

Specified by:

getPassword in interface com.jcraft.jsch.UserInfo

promptPassphrase

public boolean promptPassphrase(java.lang.String arg0)

Specified by:

promptPassphrase in interface com.jcraft.jsch.UserInfo

promptPassword

public boolean promptPassword(java.lang.String arg0)

Specified by:

promptPassword in interface com.jcraft.jsch.UserInfo

promptYesNo

public boolean promptYesNo(java.lang.String arg0)

Specified by:

promptYesNo in interface com.jcraft.jsch.UserInfo

showMessage

public void showMessage(java.lang.String arg0)

Specified by:

showMessage in interface com.jcraft.jsch.UserInfo

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:
from .engine import conf, gfx
from .engine.game import World
from .engine.entity import Entity

class Level (World):
    def init (self):
        pass


text:
<?php

declare(strict_types=1);

namespace Leapt\ImBundle\Twig\Extension;

use Leapt\ImBundle\Manager;
use Leapt\ImBundle\Twig\TokenParser\Imresize as ImResizeTokenParser;
use Symfony\Component\DomCrawler\Crawler;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use Twig\TwigFunction;

class ImExtension extends AbstractExtension
{
    public function __construct(private Manager $manager)
    {
    }

    public function getTokenParsers(): array
    {
        return [
            new ImResizeTokenParser(),
        ];
    }

    public function getFilters(): array
    {
        return [
            new TwigFilter('imresize', [$this, 'imResize'], ['pre_escape' => 'html', 'is_safe' => ['html']]),
        ];
    }

    public function getFunctions(): array
    {
        return [
            new TwigFunction('imresize', [$this, 'imResize'], ['pre_escape' => 'html', 'is_safe' => ['html']]),
        ];
    }

    /**
     * Called by the compile method to replace the image sources with image cache sources.
     */
    public function convert(string $html): string
    {
        preg_match_all('|<img ([^>]+)>|', $html, $matches);

        foreach ($matches[0] as $img) {
            $crawler = new Crawler();
            $crawler->addContent($img);
            $imgTag = $crawler->filter('img');

            $src = $imgTag->attr('src');
            \assert(\is_string($src));
            $width = $imgTag->attr('width');
            $height = $imgTag->attr('height');

            if (!empty($width) || !empty($height)) {
                $format = $width . 'x' . $height;
                $updatedTagString = preg_replace("| src=[\"']" . $src . "[\"']|", ' src="' . $this->imResize($src, $format) . '"', $img);
                $html = str_replace($img, $updatedTagString, $html);
            }
        }

        return $html;
    }

    /**
     * Returns the cached path, after executing the asset twig function.
     */
    public function imResize(string $path, string $format): string
    {
        // Remove extra whitespaces
        $path = trim($path);

        $separator = '';
        // Transform absolute url to custom url like : http/ or https/ or simply /
        if (str_starts_with($path, 'http://') || str_starts_with($path, 'https://') || str_starts_with($path, '//')) {
            $path = str_replace(['://', '//'], '/', $path);
        } elseif (str_starts_with($path, '/')) {
            // If the path started with a slash, we will add it at the start of the path result
            $separator = '/';
        }

        // Remove the first slash, as we add it manually
        $path = ltrim($path, '/');

        return $separator . $this->manager->getCachePath() . '/' . $format . '/' . $path;
    }

    public function getName(): string
    {
        return 'leapt_im';
    }
}


text:
<?php
namespace TestApp\Model\Entity\PHP7;

use Cake\ORM\Entity;

class Virtual extends Entity {

	protected function _getVirtualOne(): ?string {
		return 'Virtual One';
	}

	protected function _getVirtualTwo(): string {
		return 'Virtual Two';
	}

}


text:
var Player = require('./player');
var Listener = require('./listener');
var LevelOneLayout = require('./level-one-layout');
var Detector = require('./detector');
var UserInfoDraw = require('./user-info-draw');

function LevelOne (canvas, score) {
  this.blocks = [];
  this.projectiles = {blue: null, orange: null};
  this.firstPlayer = new Player({x: 300, y: 500});
  this.listener = new Listener(canvas, this.firstPlayer, this.projectiles, score);
  this.level = new LevelOneLayout(this.blocks);
  this.detector = new Detector(this.firstPlayer, this.blocks, this.projectiles);
  this.userInfoDraw = new UserInfoDraw();
  this.listener.setListeners();
  this.level.buildLevel();
}

module.exports = LevelOne;