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

#ifndef BITCOIN_WALLET_H
#define BITCOIN_WALLET_H

#include "addressbook.h"
#include "amount.h"
#include "base58.h"
#include "crypter.h"
#include "kernel.h"
#include "key.h"
#include "keystore.h"
#include "main.h"
#include "pairresult.h"
#include "primitives/block.h"
#include "primitives/transaction.h"
#include "zpiv/zerocoin.h"
#include "guiinterface.h"
#include "util.h"
#include "validationinterface.h"
#include "wallet/wallet_ismine.h"
#include "wallet/walletdb.h"
#include "zpiv/zpivmodule.h"
#include "zpiv/zpivwallet.h"
#include "zpiv/zpivtracker.h"

#include <algorithm>
#include <map>
#include <set>
#include <stdexcept>
#include <stdint.h>
#include <string>
#include <utility>
#include <vector>

/**
 * Settings
 */
extern CFeeRate payTxFee;
extern CAmount maxTxFee;
extern unsigned int nTxConfirmTarget;
extern bool bSpendZeroConfChange;
extern bool bdisableSystemnotifications;
extern bool fSendFreeTransactions;
extern bool fPayAtLeastCustomFee;

//! -paytxfee default
static const CAmount DEFAULT_TRANSACTION_FEE = 0;
//! -paytxfee will warn if called with a higher fee than this amount (in satoshis) per KB
static const CAmount nHighTransactionFeeWarning = 0.1 * COIN;
//! -maxtxfee default
static const CAmount DEFAULT_TRANSACTION_MAXFEE = 1 * COIN;
//! -maxtxfee will warn if called with a higher fee than this amount (in satoshis)
static const CAmount nHighTransactionMaxFeeWarning = 100 * nHighTransactionFeeWarning;
//! Largest (in bytes) free transaction we're willing to create
static const unsigned int MAX_FREE_TRANSACTION_CREATE_SIZE = 1000;
//! -custombackupthreshold default
static const int DEFAULT_CUSTOMBACKUPTHRESHOLD = 1;

class CAccountingEntry;
class CCoinControl;
class COutput;
class CReserveKey;
class CScript;
class CWalletTx;

/** (client) version numbers for particular wallet features */
enum WalletFeature {
    FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output)

    FEATURE_WALLETCRYPT = 40000, // wallet encryption
    FEATURE_COMPRPUBKEY = 60000, // compressed public keys

    FEATURE_LATEST = 61000
};

enum AvailableCoinsType {
    ALL_COINS = 1,
    ONLY_DENOMINATED = 2,
    ONLY_NOT10000IFMN = 3,
    ONLY_NONDENOMINATED_NOT10000IFMN = 4,           // ONLY_NONDENOMINATED and not 10000 PIV at the same time
    ONLY_10000 = 5,                                 // find masternode outputs including locked ones (use with caution)
    STAKEABLE_COINS = 6                             // UTXO's that are valid for staking
};

// Possible states for zPIV send
enum ZerocoinSpendStatus {
    ZPIV_SPEND_OKAY = 0,                            // No error
    ZPIV_SPEND_ERROR = 1,                           // Unspecified class of errors, more details are (hopefully) in the returning text
    ZPIV_WALLET_LOCKED = 2,                         // Wallet was locked
    ZPIV_COMMIT_FAILED = 3,                         // Commit failed, reset status
    ZPIV_ERASE_SPENDS_FAILED = 4,                   // Erasing spends during reset failed
    ZPIV_ERASE_NEW_MINTS_FAILED = 5,                // Erasing new mints during reset failed
    ZPIV_TRX_FUNDS_PROBLEMS = 6,                    // Everything related to available funds
    ZPIV_TRX_CREATE = 7,                            // Everything related to create the transaction
    ZPIV_TRX_CHANGE = 8,                            // Everything related to transaction change
    ZPIV_TXMINT_GENERAL = 9,                        // General errors in MintToTxIn
    ZPIV_INVALID_COIN = 10,                         // Selected mint coin is not valid
    ZPIV_FAILED_ACCUMULATOR_INITIALIZATION = 11,    // Failed to initialize witness
    ZPIV_INVALID_WITNESS = 12,                      // Spend coin transaction did not verify
    ZPIV_BAD_SERIALIZATION = 13,                    // Transaction verification failed
    ZPIV_SPENT_USED_ZPIV = 14,                      // Coin has already been spend
    ZPIV_TX_TOO_LARGE = 15,                          // The transaction is larger than the max tx size
    ZPIV_SPEND_V1_SEC_LEVEL                         // Spend is V1 and security level is not set to 100
};

struct CompactTallyItem {
    CBitcoinAddress address;
    CAmount nAmount;
    std::vector<CTxIn> vecTxIn;
    CompactTallyItem()
    {
        nAmount = 0;
    }
};

/** A key pool entry */
class CKeyPool
{
public:
    int64_t nTime;
    CPubKey vchPubKey;

    CKeyPool();
    CKeyPool(const CPubKey& vchPubKeyIn);

    ADD_SERIALIZE_METHODS;

    template <typename Stream, typename Operation>
    inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
    {
        if (!(nType & SER_GETHASH))
            READWRITE(nVersion);
        READWRITE(nTime);
        READWRITE(vchPubKey);
    }
};

/** Record info about last kernel stake operation (time and chainTip)**/
class CStakerStatus {
private:
    const CBlockIndex* tipLastStakeAttempt = nullptr;
    int64_t timeLastStakeAttempt;
public:
    const CBlockIndex* GetLastTip() const { return tipLastStakeAttempt; }
    uint256 GetLastHash() const
    {
        return (tipLastStakeAttempt == nullptr ? 0 : tipLastStakeAttempt->GetBlockHash());
    }
    int64_t GetLastTime() const { return timeLastStakeAttempt; }
    void SetLastTip(const CBlockIndex* lastTip) { tipLastStakeAttempt = lastTip; }
    void SetLastTime(const uint64_t lastTime) { timeLastStakeAttempt = lastTime; }
    void SetNull()
    {
        SetLastTip(nullptr);
        SetLastTime(0);
    }
    bool IsActive() { return (timeLastStakeAttempt + 30) >= GetTime(); }
};

/**
 * A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
 * and provides the ability to create new transactions.
 */
class CWallet : public CCryptoKeyStore, public CValidationInterface
{
private:
    bool SelectCoins(const CAmount& nTargetValue, std::set<std::pair<const CWalletTx*, unsigned int> >& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl = NULL, AvailableCoinsType coin_type = ALL_COINS, bool useIX = true, bool fIncludeColdStaking=false, bool fIncludeDelegated=true) const;
    //it was public bool SelectCoins(int64_t nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet, const CCoinControl *coinControl = NULL, AvailableCoinsType coin_type=ALL_COINS, bool useIX = true) const;

    CWalletDB* pwalletdbEncryption;

    //! the current wallet version: clients below this version are not able to load the wallet
    int nWalletVersion;

    //! the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
    int nWalletMaxVersion;

    int64_t nNextResend;
    int64_t nLastResend;

    /**
     * Used to keep track of spent outpoints, and
     * detect and report conflicts (double-spends or
     * mutated transactions where the mutant gets mined).
     */
    typedef std::multimap<COutPoint, uint256> TxSpends;
    TxSpends mapTxSpends;
    void AddToSpends(const COutPoint& outpoint, const uint256& wtxid);
    void AddToSpends(const uint256& wtxid);

    /* Mark a transaction (and its in-wallet descendants) as conflicting with a particular block. */
    void MarkConflicted(const uint256& hashBlock, const uint256& hashTx);

    void SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator>);

public:

    static const int STAKE_SPLIT_THRESHOLD = 2000;

    bool StakeableCoins(std::vector<COutput>* pCoins = nullptr);
    bool IsCollateralAmount(CAmount nInputAmount) const;

    // Zerocoin additions
    bool CreateZerocoinMintTransaction(const CAmount nValue, CMutableTransaction& txNew, std::vector<CDeterministicMint>& vDMints, CReserveKey* reservekey, int64_t& nFeeRet, std::string& strFailReason, const CCoinControl* coinControl = NULL, const bool isZCSpendChange = false);

    bool CreateZerocoinSpendTransaction(
            CAmount nValue,
            CWalletTx& wtxNew,
            CReserveKey& reserveKey,
            CZerocoinSpendReceipt& receipt,
            std::vector<CZerocoinMint>& vSelectedMints,
            std::vector<CDeterministicMint>& vNewMints,
            bool fMintChange,
            bool fMinimizeChange,
            std::list<std::pair<CBitcoinAddress*,CAmount>> addressesTo,
            CBitcoinAddress* changeAddress = nullptr,
            bool isPublicSpend = true);

    bool CheckCoinSpend(libzerocoin::CoinSpend& spend, libzerocoin::Accumulator& accumulator, CZerocoinSpendReceipt& receipt);
    bool MintToTxIn(CZerocoinMint zerocoinSelected, const uint256& hashTxOut, CTxIn& newTxIn, CZerocoinSpendReceipt& receipt, libzerocoin::SpendType spendType, CBlockIndex* pindexCheckpoint = nullptr, bool isPublicSpend = true);
    bool MintsToInputVector(std::map<CBigNum, CZerocoinMint>& mapMintsSelected, const uint256& hashTxOut, std::vector<CTxIn>& vin,
                            CZerocoinSpendReceipt& receipt, libzerocoin::SpendType spendType, CBlockIndex* pindexCheckpoint = nullptr);
    // Public coin spend input creation
    bool MintsToInputVectorPublicSpend(std::map<CBigNum, CZerocoinMint>& mapMintsSelected, const uint256& hashTxOut, std::vector<CTxIn>& vin,
                                       CZerocoinSpendReceipt& receipt, libzerocoin::SpendType spendType, CBlockIndex* pindexCheckpoint = nullptr);

    std::string MintZerocoinFromOutPoint(CAmount nValue, CWalletTx& wtxNew, std::vector<CDeterministicMint>& vDMints, const std::vector<COutPoint> vOutpts);
    std::string MintZerocoin(CAmount nValue, CWalletTx& wtxNew, std::vector<CDeterministicMint>& vDMints, const CCoinControl* coinControl = NULL);

    bool SpendZerocoin(
            CAmount nAmount,
            CWalletTx& wtxNew,
            CZerocoinSpendReceipt& receipt,
            std::vector<CZerocoinMint>& vMintsSelected,
            bool fMintChange,
            bool fMinimizeChange,
            std::list<std::pair<CBitcoinAddress*,CAmount>> addressesTo,
            CBitcoinAddress* changeAddress = nullptr,
            bool isPublicSpend = true
    );

    std::string ResetMintZerocoin();
    std::string ResetSpentZerocoin();
    void ReconsiderZerocoins(std::list<CZerocoinMint>& listMintsRestored, std::list<CDeterministicMint>& listDMintsRestored);
    void ZPivBackupWallet();
    bool GetZerocoinKey(const CBigNum& bnSerial, CKey& key);
    bool CreateZPIVOutPut(libzerocoin::CoinDenomination denomination, CTxOut& outMint, CDeterministicMint& dMint);
    bool GetMint(const uint256& hashSerial, CZerocoinMint& mint);
    bool GetMintFromStakeHash(const uint256& hashStake, CZerocoinMint& mint);
    bool DatabaseMint(CDeterministicMint& dMint);
    bool SetMintUnspent(const CBigNum& bnSerial);
    bool UpdateMint(const CBigNum& bnValue, const int& nHeight, const uint256& txid, const libzerocoin::CoinDenomination& denom);
    std::string GetUniqueWalletBackupName(bool fzpivAuto) const;

    /** Zerocin entry changed.
    * @note called with lock cs_wallet held.
    */
    boost::signals2::signal<void(CWallet* wallet, const std::string& pubCoin, const std::string& isUsed, ChangeType status)> NotifyZerocoinChanged;
    /*
     * Main wallet lock.
     * This lock protects all the fields added by CWallet
     *   except for:
     *      fFileBacked (immutable after instantiation)
     *      strWalletFile (immutable after instantiation)
     */
    mutable CCriticalSection cs_wallet;

    CzPIVWallet* zwalletMain;

    bool fFileBacked;
    bool fWalletUnlockAnonymizeOnly;
    std::string strWalletFile;
    bool fBackupMints;
    std::unique_ptr<CzPIVTracker> zpivTracker;

    std::set<int64_t> setKeyPool;
    std::map<CKeyID, CKeyMetadata> mapKeyMetadata;

    typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
    MasterKeyMap mapMasterKeys;
    unsigned int nMasterKeyMaxID;

    // Stake Settings
    uint64_t nStakeSplitThreshold;
    int nStakeSetUpdateTime;
    CStakerStatus* pStakerStatus = nullptr;

    //MultiSend
    std::vector<std::pair<std::string, int> > vMultiSend;
    bool fMultiSendStake;
    bool fMultiSendMasternodeReward;
    bool fMultiSendNotify;
    std::string strMultiSendChangeAddress;
    int nLastMultiSendHeight;
    std::vector<std::string> vDisabledAddresses;

    //Auto Combine Inputs
    bool fCombineDust;
    CAmount nAutoCombineThreshold;

    CWallet();
    CWallet(std::string strWalletFileIn);
    ~CWallet();
    void SetNull();
    void setZWallet(CzPIVWallet* zwallet);
    CzPIVWallet* getZWallet();
    void setZPivAutoBackups(bool fEnabled);
    bool isMultiSendEnabled();
    void setMultiSendDisabled();

    std::map<uint256, CWalletTx> mapWallet;
    std::list<CAccountingEntry> laccentries;

    typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
    typedef std::multimap<int64_t, TxPair > TxItems;
    TxItems wtxOrdered;

    int64_t nOrderPosNext;
    std::map<uint256, int> mapRequestCount;

    std::map<CTxDestination, AddressBook::CAddressBookData> mapAddressBook;

    std::set<COutPoint> setLockedCoins;

    int64_t nTimeFirstKey;

    const CWalletTx* GetWalletTx(const uint256& hash) const;

    std::vector<CWalletTx> getWalletTxs();

    //! check whether we are allowed to upgrade (or already support) to the named feature
    bool CanSupportFeature(enum WalletFeature wf);

    bool AvailableCoins(std::vector<COutput>* pCoins, bool fOnlyConfirmed = true, const CCoinControl* coinControl = NULL, bool fIncludeZeroValue = false, AvailableCoinsType nCoinType = ALL_COINS, bool fUseIX = false, int nWatchonlyConfig = 1, bool fIncludeColdStaking=false, bool fIncludeDelegated=true) const;

    // Get available p2cs utxo
    void GetAvailableP2CSCoins(std::vector<COutput>& vCoins) const;

    std::map<CBitcoinAddress, std::vector<COutput> > AvailableCoinsByAddress(bool fConfirmed = true, CAmount maxCoinValue = 0);
    bool SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, std::vector<COutput> vCoins, std::set<std::pair<const CWalletTx*, unsigned int> >& setCoinsRet, CAmount& nValueRet) const;

    /// Get 10000 PIV output and keys which can be used for the Masternode
    bool GetMasternodeVinAndKeys(CTxIn& txinRet, CPubKey& pubKeyRet, CKey& keyRet, std::string strTxHash = "", std::string strOutputIndex = "");
    /// Extract txin information and keys from output
    bool GetVinAndKeysFromOutput(COutput out, CTxIn& txinRet, CPubKey& pubKeyRet, CKey& keyRet, bool fColdStake = false);

    bool IsSpent(const uint256& hash, unsigned int n) const;

    bool IsLockedCoin(const uint256& hash, unsigned int n) const;
    void LockCoin(const COutPoint& output);
    void UnlockCoin(const COutPoint& output);
    void UnlockAllCoins();
    void ListLockedCoins(std::vector<COutPoint>& vOutpts);

    //  keystore implementation
    // Generate a new key
    CPubKey GenerateNewKey();
    PairResult getNewAddress(CBitcoinAddress& ret, const std::string addressLabel, const std::string purpose,
                                           const CChainParams::Base58Type addrType = CChainParams::PUBKEY_ADDRESS);
    PairResult getNewAddress(CBitcoinAddress& ret, std::string label);
    PairResult getNewStakingAddress(CBitcoinAddress& ret, std::string label);
    int64_t GetKeyCreationTime(CPubKey pubkey);
    int64_t GetKeyCreationTime(const CBitcoinAddress& address);

    //! Adds a key to the store, and saves it to disk.
    bool AddKeyPubKey(const CKey& key, const CPubKey& pubkey);
    //! Adds a key to the store, without saving it to disk (used by LoadWallet)
    bool LoadKey(const CKey& key, const CPubKey& pubkey) { return CCryptoKeyStore::AddKeyPubKey(key, pubkey); }
    //! Load metadata (used by LoadWallet)
    bool LoadKeyMetadata(const CPubKey& pubkey, const CKeyMetadata& metadata);

    bool LoadMinVersion(int nVersion);

    //! Adds an encrypted key to the store, and saves it to disk.
    bool AddCryptedKey(const CPubKey& vchPubKey, const std::vector<unsigned char>& vchCryptedSecret);
    //! Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
    bool LoadCryptedKey(const CPubKey& vchPubKey, const std::vector<unsigned char>& vchCryptedSecret);
    bool AddCScript(const CScript& redeemScript);
    bool LoadCScript(const CScript& redeemScript);

    //! Adds a destination data tuple to the store, and saves it to disk
    bool AddDestData(const CTxDestination& dest, const std::string& key, const std::string& value);
    //! Erases a destination data tuple in the store and on disk
    bool EraseDestData(const CTxDestination& dest, const std::string& key);
    //! Adds a destination data tuple to the store, without saving it to disk
    bool LoadDestData(const CTxDestination& dest, const std::string& key, const std::string& value);

    //! Adds a watch-only address to the store, and saves it to disk.
    bool AddWatchOnly(const CScript& dest);
    bool RemoveWatchOnly(const CScript& dest);
    //! Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
    bool LoadWatchOnly(const CScript& dest);

    //! Adds a MultiSig address to the store, and saves it to disk.
    bool AddMultiSig(const CScript& dest);
    bool RemoveMultiSig(const CScript& dest);
    //! Adds a MultiSig address to the store, without saving it to disk (used by LoadWallet)
    bool LoadMultiSig(const CScript& dest);

    bool Unlock(const SecureString& strWalletPassphrase, bool anonimizeOnly = false);
    bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
    bool EncryptWallet(const SecureString& strWalletPassphrase);

    void GetKeyBirthTimes(std::map<CKeyID, int64_t>& mapKeyBirth) const;
    unsigned int ComputeTimeSmart(const CWalletTx& wtx) const;

    /**
     * Increment the next transaction order id
     * @return next transaction order id
     */
    int64_t IncOrderPosNext(CWalletDB* pwalletdb = NULL);

    void MarkDirty();
    bool AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet, CWalletDB* pwalletdb);
    void SyncTransaction(const CTransaction& tx, const CBlock* pblock);
    bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate);
    void EraseFromWallet(const uint256& hash);
    int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false, bool fromStartup = false);
    void ReacceptWalletTransactions(bool fFirstLoad = false);
    void ResendWalletTransactions();

    CAmount loopTxsBalance(std::function<void(const uint256&, const CWalletTx&, CAmount&)>method) const;
    CAmount GetBalance() const;
    CAmount GetColdStakingBalance() const;  // delegated coins for which we have the staking key
    CAmount GetImmatureColdStakingBalance() const;
    CAmount GetStakingBalance(const bool fIncludeColdStaking = true) const;
    CAmount GetDelegatedBalance() const;    // delegated coins for which we have the spending key
    CAmount GetImmatureDelegatedBalance() const;
    CAmount GetZerocoinBalance(bool fMatureOnly) const;
    CAmount GetUnconfirmedZerocoinBalance() const;
    CAmount GetImmatureZerocoinBalance() const;
    CAmount GetLockedCoins() const;
    CAmount GetUnlockedCoins() const;
    std::map<libzerocoin::CoinDenomination, CAmount> GetMyZerocoinDistribution() const;
    CAmount GetUnconfirmedBalance() const;
    CAmount GetImmatureBalance() const;
    CAmount GetWatchOnlyBalance() const;
    CAmount GetUnconfirmedWatchOnlyBalance() const;
    CAmount GetImmatureWatchOnlyBalance() const;
    CAmount GetLockedWatchOnlyBalance() const;
    bool CreateTransaction(const std::vector<std::pair<CScript, CAmount> >& vecSend,
        CWalletTx& wtxNew,
        CReserveKey& reservekey,
        CAmount& nFeeRet,
        std::string& strFailReason,
        const CCoinControl* coinControl = NULL,
        AvailableCoinsType coin_type = ALL_COINS,
        bool useIX = false,
        CAmount nFeePay = 0,
        bool fIncludeDelegated = false);
    bool CreateTransaction(CScript scriptPubKey, const CAmount& nValue, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, std::string& strFailReason, const CCoinControl* coinControl = NULL, AvailableCoinsType coin_type = ALL_COINS, bool useIX = false, CAmount nFeePay = 0, bool fIncludeDelegated = false);
    bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, std::string strCommand = "tx");
    bool AddAccountingEntry(const CAccountingEntry&, CWalletDB & pwalletdb);
    int GenerateObfuscationOutputs(int nTotalValue, std::vector<CTxOut>& vout);
    bool CreateCoinStake(const CKeyStore& keystore, const CBlockIndex* pindexPrev, unsigned int nBits, CMutableTransaction& txNew, int64_t& nTxNewTime);
    bool MultiSend();
    void AutoCombineDust();

    static CFeeRate minTxFee;
    static CAmount GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool);

    bool NewKeyPool();
    bool TopUpKeyPool(unsigned int kpSize = 0);
    void ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool);
    void KeepKey(int64_t nIndex);
    void ReturnKey(int64_t nIndex);
    bool GetKeyFromPool(CPubKey& key);
    int64_t GetOldestKeyPoolTime();
    void GetAllReserveKeys(std::set<CKeyID>& setAddress) const;

    std::set<std::set<CTxDestination> > GetAddressGroupings();
    std::map<CTxDestination, CAmount> GetAddressBalances();

    std::set<CTxDestination> GetAccountAddresses(std::string strAccount) const;

    bool GetBudgetSystemCollateralTX(CWalletTx& tx, uint256 hash, bool useIX);
    bool GetBudgetFinalizationCollateralTX(CWalletTx& tx, uint256 hash, bool useIX); // Only used for budget finalization

    bool IsDenominated(const CTxIn& txin) const;

    bool IsDenominatedAmount(CAmount nInputAmount) const;

    bool IsUsed(const CBitcoinAddress address) const;

    isminetype IsMine(const CTxIn& txin) const;
    CAmount GetDebit(const CTxIn& txin, const isminefilter& filter) const;
    isminetype IsMine(const CTxOut& txout) const;
    bool IsMyZerocoinSpend(const CBigNum& bnSerial) const;
    bool IsMyMint(const CBigNum& bnValue) const;
    CAmount GetCredit(const CTxOut& txout, const isminefilter& filter) const;
    bool IsChange(const CTxOut& txout) const;
    CAmount GetChange(const CTxOut& txout) const;
    bool IsMine(const CTransaction& tx) const;
    /** should probably be renamed to IsRelevantToMe */
    bool IsFromMe(const CTransaction& tx) const;
    CAmount GetDebit(const CTransaction& tx, const isminefilter& filter) const;
    CAmount GetCredit(const CTransaction& tx, const isminefilter& filter, const bool fUnspent = false) const;
    CAmount GetChange(const CTransaction& tx) const;
    void SetBestChain(const CBlockLocator& loc);

    DBErrors LoadWallet(bool& fFirstRunRet);
    DBErrors ZapWalletTx(std::vector<CWalletTx>& vWtx);

    static CBitcoinAddress ParseIntoAddress(const CTxDestination& dest, const std::string& purpose);

    bool SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& purpose);
    bool DelAddressBook(const CTxDestination& address, const CChainParams::Base58Type addrType = CChainParams::PUBKEY_ADDRESS);
    bool HasAddressBook(const CTxDestination& address) const;
    bool HasDelegator(const CTxOut& out) const;

    std::string purposeForAddress(const CTxDestination& address) const;

    bool UpdatedTransaction(const uint256& hashTx);

    void Inventory(const uint256& hash);

    unsigned int GetKeyPoolSize();

    //! signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
    bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);

    //! change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
    bool SetMaxVersion(int nVersion);

    //! get the current wallet format (the oldest client version guaranteed to understand this wallet)
    int GetVersion();

    //! Get wallet transactions that conflict with given transaction (spend same outputs)
    std::set<uint256> GetConflicts(const uint256& txid) const;

    /* Mark a transaction (and it in-wallet descendants) as abandoned so its inputs may be respent. */
    bool AbandonTransaction(const uint256& hashTx);

    /**
     * Address book entry changed.
     * @note called with lock cs_wallet held.
     */
    boost::signals2::signal<void(CWallet* wallet, const CTxDestination& address, const std::string& label, bool isMine, const std::string& purpose, ChangeType status)> NotifyAddressBookChanged;

    /**
     * Wallet transaction added, removed or updated.
     * @note called with lock cs_wallet held.
     */
    boost::signals2::signal<void(CWallet* wallet, const uint256& hashTx, ChangeType status)> NotifyTransactionChanged;

    /** Show progress e.g. for rescan */
    boost::signals2::signal<void(const std::string& title, int nProgress)> ShowProgress;

    /** Watch-only address added */
    boost::signals2::signal<void(bool fHaveWatchOnly)> NotifyWatchonlyChanged;

    /** MultiSig address added */
    boost::signals2::signal<void(bool fHaveMultiSig)> NotifyMultiSigChanged;

    /** zPIV reset */
    boost::signals2::signal<void()> NotifyzPIVReset;

    /** notify wallet file backed up */
    boost::signals2::signal<void (const bool& fSuccess, const std::string& filename)> NotifyWalletBacked;
};

/** A key allocated from the key pool. */
class CReserveKey
{
protected:
    CWallet* pwallet;
    int64_t nIndex;
    CPubKey vchPubKey;

public:
    CReserveKey(CWallet* pwalletIn)
    {
        nIndex = -1;
        pwallet = pwalletIn;
    }

    ~CReserveKey()
    {
        ReturnKey();
    }

    void ReturnKey();
    bool GetReservedKey(CPubKey& pubkey);
    void KeepKey();
};

typedef std::map<std::string, std::string> mapValue_t;

static void ReadOrderPos(int64_t& nOrderPos, mapValue_t& mapValue)
{
    if (!mapValue.count("n")) {
        nOrderPos = -1; // TODO: calculate elsewhere
        return;
    }
    nOrderPos = atoi64(mapValue["n"].c_str());
}

static void WriteOrderPos(const int64_t& nOrderPos, mapValue_t& mapValue)
{
    if (nOrderPos == -1)
        return;
    mapValue["n"] = i64tostr(nOrderPos);
}

struct COutputEntry {
    CTxDestination destination;
    CAmount amount;
    int vout;
};

/** A transaction with a merkle branch linking it to the block chain. */
class CMerkleTx : public CTransaction
{
private:
    /** Constant used in hashBlock to indicate tx has been abandoned */
    static const uint256 ABANDON_HASH;

public:
    uint256 hashBlock;
    /* An nIndex == -1 means that hashBlock (in nonzero) refers to the earliest
     * block in the chain we know this or any in-wallet dependency conflicts
     * with. Older clients interpret nIndex == -1 as unconfirmed for backward
     * compatibility.
     */
    int nIndex;

    CMerkleTx()
    {
        Init();
    }

    CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
    {
        Init();
    }

    void Init()
    {
        hashBlock = 0;
        nIndex = -1;
    }

    ADD_SERIALIZE_METHODS;

    template <typename Stream, typename Operation>
    inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
    {
        std::vector<uint256> vMerkleBranch; // For compatibility with older versions.
        READWRITE(*(CTransaction*)this);
        nVersion = this->nVersion;
        READWRITE(hashBlock);
        READWRITE(vMerkleBranch);
        READWRITE(nIndex);
    }

    int SetMerkleBranch(const CBlock& block);

    /**
     * Return depth of transaction in blockchain:
     * <0  : conflicts with a transaction this deep in the blockchain
     *  0  : in memory pool, waiting to be included in a block
     * >=1 : this many blocks deep in the main chain
     */
    int GetDepthInMainChain(const CBlockIndex*& pindexRet, bool enableIX = true) const;
    int GetDepthInMainChain(bool enableIX = true) const
    {
        const CBlockIndex* pindexRet;
        return GetDepthInMainChain(pindexRet, enableIX);
    }
    bool IsInMainChain() const
    {
        const CBlockIndex* pindexRet;
        return GetDepthInMainChain(pindexRet, false) > 0;
    }
    int GetBlocksToMaturity() const;
    bool AcceptToMemoryPool(bool fLimitFree = true, bool fRejectInsaneFee = true, bool ignoreFees = false);
    int GetTransactionLockSignatures() const;
    bool IsTransactionLockTimedOut() const;
    bool hashUnset() const { return (hashBlock.IsNull() || hashBlock == ABANDON_HASH); }
    bool isAbandoned() const { return (hashBlock == ABANDON_HASH); }
    void setAbandoned() { hashBlock = ABANDON_HASH; }
};

/**
 * A transaction with a bunch of additional info that only the owner cares about.
 * It includes any unrecorded transactions needed to link it back to the block chain.
 */
class CWalletTx : public CMerkleTx
{
private:
    const CWallet* pwallet;

public:
    mapValue_t mapValue;
    std::vector<std::pair<std::string, std::string> > vOrderForm;
    unsigned int fTimeReceivedIsTxTime;
    unsigned int nTimeReceived; //! time received by this node
    unsigned int nTimeSmart;
    char fFromMe;
    std::string strFromAccount;
    int64_t nOrderPos; //! position in ordered transaction list

    // memory only
    mutable bool fDebitCached;
    mutable bool fCreditCached;
    mutable bool fImmatureCreditCached;
    mutable bool fAvailableCreditCached;
    mutable bool fAnonymizableCreditCached;
    mutable bool fAnonymizedCreditCached;
    mutable bool fDenomUnconfCreditCached;
    mutable bool fDenomConfCreditCached;
    mutable bool fWatchDebitCached;
    mutable bool fWatchCreditCached;
    mutable bool fImmatureWatchCreditCached;
    mutable bool fAvailableWatchCreditCached;
    mutable bool fChangeCached;
    mutable bool fColdDebitCached;
    mutable bool fColdCreditCached;
    mutable bool fDelegatedDebitCached;
    mutable bool fDelegatedCreditCached;
    mutable bool fStakeDelegationVoided;
    mutable CAmount nDebitCached;
    mutable CAmount nCreditCached;
    mutable CAmount nImmatureCreditCached;
    mutable CAmount nAvailableCreditCached;
    mutable CAmount nAnonymizableCreditCached;
    mutable CAmount nAnonymizedCreditCached;
    mutable CAmount nDenomUnconfCreditCached;
    mutable CAmount nDenomConfCreditCached;
    mutable CAmount nWatchDebitCached;
    mutable CAmount nWatchCreditCached;
    mutable CAmount nImmatureWatchCreditCached;
    mutable CAmount nAvailableWatchCreditCached;
    mutable CAmount nChangeCached;
    mutable CAmount nColdDebitCached;
    mutable CAmount nColdCreditCached;
    mutable CAmount nDelegatedDebitCached;
    mutable CAmount nDelegatedCreditCached;

    CWalletTx();
    CWalletTx(const CWallet* pwalletIn);
    CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn);
    CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn);
    void Init(const CWallet* pwalletIn);

    ADD_SERIALIZE_METHODS;

    template <typename Stream, typename Operation>
    inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
    {
        if (ser_action.ForRead())
            Init(NULL);
        char fSpent = false;

        if (!ser_action.ForRead()) {
            mapValue["fromaccount"] = strFromAccount;

            WriteOrderPos(nOrderPos, mapValue);

            if (nTimeSmart)
                mapValue["timesmart"] = strprintf("%u", nTimeSmart);
        }

        READWRITE(*(CMerkleTx*)this);
        std::vector<CMerkleTx> vUnused; //! Used to be vtxPrev
        READWRITE(vUnused);
        READWRITE(mapValue);
        READWRITE(vOrderForm);
        READWRITE(fTimeReceivedIsTxTime);
        READWRITE(nTimeReceived);
        READWRITE(fFromMe);
        READWRITE(fSpent);

        if (ser_action.ForRead()) {
            strFromAccount = mapValue["fromaccount"];

            ReadOrderPos(nOrderPos, mapValue);

            nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(mapValue["timesmart"]) : 0;
        }

        mapValue.erase("fromaccount");
        mapValue.erase("version");
        mapValue.erase("spent");
        mapValue.erase("n");
        mapValue.erase("timesmart");
    }

    //! make sure balances are recalculated
    void MarkDirty();

    void BindWallet(CWallet* pwalletIn);
    //! checks whether a tx has P2CS inputs or not
    bool HasP2CSInputs() const;

    int GetDepthAndMempool(bool& fConflicted, bool enableIX = true) const;

    //! filter decides which addresses will count towards the debit
    CAmount GetDebit(const isminefilter& filter) const;
    CAmount GetCredit(const isminefilter& filter) const;
    CAmount GetUnspentCredit(const isminefilter& filter) const;
    CAmount GetImmatureCredit(bool fUseCache = true, const isminefilter& filter = ISMINE_SPENDABLE_ALL) const;
    CAmount GetAvailableCredit(bool fUseCache = true) const;
    // Return sum of unlocked coins
    CAmount GetUnlockedCredit() const;
    // Return sum of unlocked coins
    CAmount GetLockedCredit() const;
    CAmount GetImmatureWatchOnlyCredit(const bool& fUseCache = true) const;
    CAmount GetAvailableWatchOnlyCredit(const bool& fUseCache = true) const;
    CAmount GetLockedWatchOnlyCredit() const;
    CAmount GetChange() const;

    // Cold staking contracts credit/debit
    CAmount GetColdStakingCredit(bool fUseCache = true) const;
    CAmount GetColdStakingDebit(bool fUseCache = true) const;
    CAmount GetStakeDelegationCredit(bool fUseCache = true) const;
    CAmount GetStakeDelegationDebit(bool fUseCache = true) const;

    // Helper method to update the amount and cacheFlag.
    CAmount UpdateAmount(CAmount& amountToUpdate, bool& cacheFlagToUpdate, bool fUseCache, isminetype mimeType, bool fCredit = true) const;

    void GetAmounts(std::list<COutputEntry>& listReceived,
        std::list<COutputEntry>& listSent,
        CAmount& nFee,
        std::string& strSentAccount,
        const isminefilter& filter) const;

    void GetAccountAmounts(const std::string& strAccount, CAmount& nReceived, CAmount& nSent, CAmount& nFee, const isminefilter& filter) const;

    bool IsFromMe(const isminefilter& filter) const;

    bool InMempool() const;

    // True if only scriptSigs are different
    bool IsEquivalentTo(const CWalletTx& tx) const;

    bool IsTrusted() const;
    bool IsTrusted(int& nDepth, bool& fConflicted) const;

    bool WriteToDisk(CWalletDB *pwalletdb);

    int64_t GetTxTime() const;
    int64_t GetComputedTxTime() const;
    int GetRequestCount() const;
    void RelayWalletTransaction(std::string strCommand = "tx");
    std::set<uint256> GetConflicts() const;
};

class COutput
{
public:
    const CWalletTx* tx;
    int i;
    int nDepth;
    bool fSpendable;

    COutput(const CWalletTx* txIn, int iIn, int nDepthIn, bool fSpendableIn)
    {
        tx = txIn;
        i = iIn;
        nDepth = nDepthIn;
        fSpendable = fSpendableIn;
    }

    //Used with Obfuscation. Will return largest nondenom, then denominations, then very small inputs
    int Priority() const
    {
        for (CAmount d : obfuScationDenominations)
            if (tx->vout[i].nValue == d) return 10000;
        if (tx->vout[i].nValue < 1 * COIN) return 20000;

        //nondenom return largest first
        return -(tx->vout[i].nValue / COIN);
    }

    CAmount Value() const
    {
        return tx->vout[i].nValue;
    }

    std::string ToString() const;
};

/** Private key that includes an expiration date in case it never gets used. */
class CWalletKey
{
public:
    CPrivKey vchPrivKey;
    int64_t nTimeCreated;
    int64_t nTimeExpires;
    std::string strComment;
    //! todo: add something to note what created it (user, getnewaddress, change)
    //!   maybe should have a map<string, string> property map

    CWalletKey(int64_t nExpires = 0);

    ADD_SERIALIZE_METHODS;

    template <typename Stream, typename Operation>
    inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
    {
        if (!(nType & SER_GETHASH))
            READWRITE(nVersion);
        READWRITE(vchPrivKey);
        READWRITE(nTimeCreated);
        READWRITE(nTimeExpires);
        READWRITE(LIMITED_STRING(strComment, 65536));
    }
};

/**
 * Account information.
 * Stored in wallet with key "acc"+string account name.
 */
class CAccount
{
public:
    CPubKey vchPubKey;

    CAccount()
    {
        SetNull();
    }

    void SetNull()
    {
        vchPubKey = CPubKey();
    }

    ADD_SERIALIZE_METHODS;

    template <typename Stream, typename Operation>
    inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
    {
        if (!(nType & SER_GETHASH))
            READWRITE(nVersion);
        READWRITE(vchPubKey);
    }
};

/**
 * Internal transfers.
 * Database key is acentry<account><counter>.
 */
class CAccountingEntry
{
public:
    std::string strAccount;
    CAmount nCreditDebit;
    int64_t nTime;
    std::string strOtherAccount;
    std::string strComment;
    mapValue_t mapValue;
    int64_t nOrderPos; //! position in ordered transaction list
    uint64_t nEntryNo;

    CAccountingEntry()
    {
        SetNull();
    }

    void SetNull()
    {
        nCreditDebit = 0;
        nTime = 0;
        strAccount.clear();
        strOtherAccount.clear();
        strComment.clear();
        nOrderPos = -1;
        nEntryNo = 0;
    }

    ADD_SERIALIZE_METHODS;

    template <typename Stream, typename Operation>
    inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
    {
        if (!(nType & SER_GETHASH))
            READWRITE(nVersion);
        //! Note: strAccount is serialized as part of the key, not here.
        READWRITE(nCreditDebit);
        READWRITE(nTime);
        READWRITE(LIMITED_STRING(strOtherAccount, 65536));

        if (!ser_action.ForRead()) {
            WriteOrderPos(nOrderPos, mapValue);

            if (!(mapValue.empty() && _ssExtra.empty())) {
                CDataStream ss(nType, nVersion);
                ss.insert(ss.begin(), '\0');
                ss << mapValue;
                ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
                strComment.append(ss.str());
            }
        }

        READWRITE(LIMITED_STRING(strComment, 65536));

        size_t nSepPos = strComment.find("\0", 0, 1);
        if (ser_action.ForRead()) {
            mapValue.clear();
            if (std::string::npos != nSepPos) {
                CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion);
                ss >> mapValue;
                _ssExtra = std::vector<char>(ss.begin(), ss.end());
            }
            ReadOrderPos(nOrderPos, mapValue);
        }
        if (std::string::npos != nSepPos)
            strComment.erase(nSepPos);

        mapValue.erase("n");
    }

private:
    std::vector<char> _ssExtra;
};

#endif // BITCOIN_WALLET_H


text:
title: Downloading the Release
description: Instructions to download the Istio release.
weight: 2
keywords: [kubernetes]
---

## Download and prepare for the installation

Istio is installed in its own `istio-system` namespace and can manage
services from all other namespaces.

1.  Go to the [Istio release](https://github.com/istio/istio/releases) page to
    download the installation file corresponding to your OS. On a macOS or
    Linux system, you can run the following command to download and
    extract the latest release automatically:

    {{< text bash >}}
    $ curl -L https://git.io/getLatestIstio | sh -
    {{< /text >}}

1.  Move to the Istio package directory. For example, if the package is
    istio-{{< istio_full_version >}}:

    {{< text bash >}}
    $ cd istio-{{< istio_full_version >}}
    {{< /text >}}

    The installation directory contains:

    * Installation `.yaml` files for Kubernetes in `install/`
    * Sample applications in `samples/`
    * The `istioctl` client binary in the `bin/` directory. `istioctl` is
      used when manually injecting Envoy as a sidecar proxy and for creating
      routing rules and policies.
    * The `istio.VERSION` configuration file

1.  Add the `istioctl` client to your PATH environment variable, on a macOS or
    Linux system:

    {{< text bash >}}
    $ export PATH=$PWD/bin:$PATH
    {{< /text >}}

redpajama_set_name: RedPajamaGithub


text:
#ifndef PPPCRYPT_H
#define PPPCRYPT_H
#include "pppdef.h"
#include <openssl/sha.h>
#include <openssl/md4.h>
#include <openssl/des.h>

VPN_PUBLIC bool DesSetkey(u_char *);
VPN_PUBLIC bool DesEncrypt(u_char *, u_char *);
VPN_PUBLIC bool DesDecrypt(u_char *, u_char *);

#endif /* PPPCRYPT_H */


text:
package ioc.tuscany;

import org.oasisopen.sca.annotation.Remotable;

@Remotable
public interface Service {

    public void foo();

    public String createFoo();
}


text:
package com.ouwenjie.note.model;

import android.content.Context;

import com.ouwenjie.note.utils.SharedPreferenceUtils;

import cn.bmob.v3.BmobUser;

/**
 *
 * Created by 文杰 on 2015/6/23.
 */
public class JideUser extends BmobUser {

    public static final String KEY_RET = "Tencent_RET";
    public static final String KEY_PAY_TOKEN = "Tencent_PAY_TOKEN";
    public static final String KEY_PF = "Tencent_PF";
    public static final String KEY_QUERY_AUTHORITY_COST = "Tencent_QUERY_AUTHORITY_COST";
    public static final String KEY_AUTHORITY_COST = "Tencent_AUTHORITY_COST";
    public static final String KEY_OPEN_ID = "Tencent_OPEN_ID";             // 关键
    public static final String KEY_EXPIRES_IN = "Tencent_EXPIRES_IN";       // 关键
    public static final String KEY_PFKEY = "Tencent_PFKEY";
    public static final String KEY_MSG = "Tencent_MSG";
    public static final String KEY_ACCESS_TOKEN = "Tencent_ACCESS_TOKEN";   // 关键
    public static final String KEY_LOGIN_COST = "Tencent_LOGIN_COST";

    public static final String KEY_EXPIRE_TIME = "Tencent_EXPIRE_TIME";

    public static final String KEY_NICK_NAME = "NICK_NAME";
    public static final String KEY_PHONE_NUMBER = "PHONE_NUMBER";
    public static final String KEY_EMAIL = "EMAIL";

    private String nickName;
    private String phoneNumber;
    private String email;

    private String expires_in;
    private String access_token;
    private String openid;
    private long expireTime;

    public String getNickName(Context context) {
        nickName = (String) SharedPreferenceUtils.get(context,KEY_NICK_NAME,"");
        return nickName;
    }

    public void setNickName(Context context, String nickName) {
        SharedPreferenceUtils.put(context,KEY_NICK_NAME,nickName);
        this.nickName = nickName;
    }

    public String getPhoneNumber(Context context) {
        phoneNumber = (String) SharedPreferenceUtils.get(context,KEY_PHONE_NUMBER,"");
        return phoneNumber;
    }

    public void setPhoneNumber(Context context, String phoneNumber) {
        SharedPreferenceUtils.put(context,KEY_PHONE_NUMBER,phoneNumber);
        this.phoneNumber = phoneNumber;
    }

    public String getEmail(Context context) {
        email = (String) SharedPreferenceUtils.get(context,KEY_EMAIL,"");
        return email;
    }

    public void setEmail(Context context, String email) {
        SharedPreferenceUtils.put(context,KEY_EMAIL,email);
        this.email = email;
    }

    public String getExpires_in(Context context) {
        expires_in = (String) SharedPreferenceUtils.get(context,KEY_EXPIRES_IN,"-1");
        return expires_in;
    }

    public void setExpires_in(Context context, String expires_in) {
        long time = System.currentTimeMillis()+Long.parseLong(expires_in)*1000;
        setExpireTime(context,time);
        SharedPreferenceUtils.put(context,KEY_EXPIRES_IN,expires_in);
        this.expires_in = expires_in;
    }

    public String getAccess_token(Context context) {
        access_token = (String) SharedPreferenceUtils.get(context,KEY_ACCESS_TOKEN,"");
        return access_token;
    }

    public void setAccess_token(Context context,String access_token) {
        SharedPreferenceUtils.put(context,KEY_ACCESS_TOKEN,access_token);
        this.access_token = access_token;
    }

    public String getOpenid(Context context) {
        openid = (String) SharedPreferenceUtils.get(context,KEY_OPEN_ID,"");
        return openid;
    }

    public void setOpenid(Context context,String openid) {
        SharedPreferenceUtils.put(context,KEY_OPEN_ID,openid);
        this.openid = openid;
    }

    public long getExpireTime(Context context) {
        expireTime = (long) SharedPreferenceUtils.get(context,KEY_EXPIRE_TIME,-1l);
        return expireTime;
    }

    public void setExpireTime(Context context, long expireTime) {
        SharedPreferenceUtils.put(context,KEY_EXPIRE_TIME,expireTime);
        this.expireTime = expireTime;
    }

    public void saveQQloginInfo(Context context, String token, String expiresId, String openId){
        setAccess_token(context, token);
        setExpires_in(context, expiresId);
        setOpenid(context, openId);
    }

    public void removeAllAuth(Context context){
        SharedPreferenceUtils.remove(context,KEY_EXPIRES_IN);
        SharedPreferenceUtils.remove(context,KEY_ACCESS_TOKEN);
        SharedPreferenceUtils.remove(context,KEY_OPEN_ID);
        SharedPreferenceUtils.remove(context,KEY_EXPIRE_TIME);

    }

    // 获取是否有登录状态改变
    public static boolean getLoginStatusChanged(Context context){
        return (boolean) SharedPreferenceUtils.get(context,"loginStatus",false);
    }

    // 设置登录状态的改变是否已被处理
    // false : 登录状态没有改变(或已被处理
    // true : 登录状态改变了(快去处理
    public static void setLoginStatusChanged(Context context, boolean status){
        SharedPreferenceUtils.put(context,"loginStatus",status);
    }

}


text:
{% import path + "/_descriptors.nunj"  as data %}

    {% set num = [2,3,4,5,6,7,8,9] | random %}
    {{ num }} descriptors

        {% set descriptors = data.descriptors | randArray %}
        {% for i in range(0,num) %}

{{ descriptors[i].label}}

        {% endfor %}

  change


text:
package com.dubture.twig.ui.editor;

import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.formatter.IContentFormatter;
import org.eclipse.jface.text.formatter.IFormattingStrategy;
import org.eclipse.jface.text.formatter.MultiPassContentFormatter;
import org.eclipse.php.ui.format.PHPFormatProcessorProxy;
import org.eclipse.wst.html.core.internal.format.HTMLFormatProcessorImpl;
import org.eclipse.wst.html.core.text.IHTMLPartitions;
import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredPartitioning;
import org.eclipse.wst.sse.ui.internal.format.StructuredFormattingStrategy;

import com.dubture.twig.core.format.TwigFormatProcessorImpl;

@SuppressWarnings("restriction")
public class TwigContentFormatter implements IContentFormatter {
	@Override
	public void format(IDocument document, IRegion region) {
		if (isFormatFile()) {
			MultiPassContentFormatter pdtFormatter = new MultiPassContentFormatter(
					IStructuredPartitioning.DEFAULT_STRUCTURED_PARTITIONING, IHTMLPartitions.HTML_DEFAULT);
			pdtFormatter.setMasterStrategy(new StructuredFormattingStrategy(new HTMLFormatProcessorImpl()));
			pdtFormatter.format(document, region);
		} else {
			StructuredTextMultiPassContentFormatter pdtFormatter = new StructuredTextMultiPassContentFormatter(
					IStructuredPartitioning.DEFAULT_STRUCTURED_PARTITIONING, IHTMLPartitions.HTML_DEFAULT);
			pdtFormatter.setMasterStrategy(new StructuredFormattingStrategy(new TwigFormatProcessorImpl()));
			pdtFormatter.format(document, region);
			// pdtFormatter.format(document, region);
		}

	}

	@Override
	public IFormattingStrategy getFormattingStrategy(String contentType) {
		// TODO Auto-generated method stub
		return null;

	}

	private boolean isFormatFile() {
		StackTraceElement[] stackTraces = new Exception().getStackTrace();
		for (StackTraceElement stackTrace : stackTraces) {
			if (stackTrace.getClassName().equals(PHPFormatProcessorProxy.class.getName())) {
				if (stackTrace.getMethodName().equals("formatFile")) {
					return true;
				}
			}
		}
		return false;
	}

}


text:
@interface CCMProjectSheetController : NSObject
{
    IBOutlet CCMUserDefaultsManager	*defaultsManager;

    IBOutlet NSPanel				*projectSheet;
	IBOutlet NSTabView				*sheetTabView;

    IBOutlet NSComboBox				*urlComboBox;
	IBOutlet NSMatrix				*serverTypeMatrix;
	IBOutlet NSProgressIndicator	*progressIndicator;
    IBOutlet NSTextField            *statusField;
    IBOutlet NSButton               *authCheckBox;
    IBOutlet NSTextField            *userField;
    IBOutlet NSTextField            *passwordField;
    IBOutlet NSButton               *continueButton;

    IBOutlet NSArrayController      *allProjectsViewController;
    IBOutlet NSArrayController		*chooseProjectsViewController;
}

- (void)beginAddSheetForWindow:(NSWindow *)aWindow;
- (void)beginEditSheetWithProject:(NSDictionary *)aProject forWindow:(NSWindow *)aWindow;
- (void)beginSheetForWindow:(NSWindow *)aWindow contextInfo:(void *)contextInfo;
- (void)sheetDidEnd:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo;

- (IBAction)historyURLSelected:(id)sender;
- (IBAction)serverDetectionChanged:(id)sender;
- (IBAction)useAuthenticationChanged:(id)sender;
- (IBAction)continueSheet:(id)sender;
- (IBAction)closeSheet:(id)sender;

- (NSString *)getValidatedURL;
- (NSString *)getCompletedAndValidatedURL;
- (NSInteger)checkURL:(NSString *)url;
- (NSArray *)convertProjectInfos:(NSArray *)projectInfos withServerUrl:(NSString *)serverUrl;
- (void)showTestInProgress:(BOOL)flag;

@end


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

<TITLE>
FinderPatternInfo
</TITLE>

<META NAME="date" CONTENT="2012-02-04">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      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

com.google.zxing.qrcode.detector

Class FinderPatternInfo

java.lang.Object
  com.google.zxing.qrcode.detector.FinderPatternInfo

public final class FinderPatternInfo
extends java.lang.Object

Encapsulates information about finder patterns in an image, including the location of
 the three finder patterns, and their estimated module size.

Author:

Sean Owen

Constructor Summary

FinderPatternInfo(FinderPattern[] patternCenters)

Method Summary

 FinderPattern
getBottomLeft()

 FinderPattern
getTopLeft()

 FinderPattern
getTopRight()

Methods inherited from class java.lang.Object

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

Constructor Detail

FinderPatternInfo

public FinderPatternInfo(FinderPattern[] patternCenters)

Method Detail

getBottomLeft

public FinderPattern getBottomLeft()

getTopLeft

public FinderPattern getTopLeft()

getTopRight

public FinderPattern getTopRight()

      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:
package weixin.guanjia.core.entity.message.customer;

public class ImageMessage extends BaseMessage {
	private Image image;

	public void setImage(Image image) {
		this.image = image;
	}

	public Image getImage() {
		return image;
	}

}


text:
.container {
	width:1205px !important;
}
.aligncenter {
	text-align:center;
}
#logo_intro {
	padding: 40px 0 0 0;
}
#slogan {
	font: 18px/22px 'Oswald', sans-serif;
	text-transform:uppercase;
	color:#000;
	margin: 10px 0 40px;
}
.wrapper {
	width:100%;
	overflow: hidden;
}
.desktop {
	position: relative;
	float:left;
	display:inline-block;
	margin: 0 5px;
	width:291px;
	height: 276px;
	background: url(../img/desktop.png) no-repeat 0 0;
	text-align:center;
}
.desktop .bg {
	width:291px;
	height: 175px;
	position:absolute;
	top:0;
	left:0;
	-webkit-transition: opacity 0.5s ease-in-out;
	-moz-transition: opacity 0.5s ease-in-out;
	-o-transition: opacity 0.5s ease-in-out;
	transition: opacity 0.5s ease-in-out;
	opacity:0;
	-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
}
.desktop .bg:hover {
	-webkit-transition: opacity 0.5s ease-in-out;
	-moz-transition: opacity 0.5s ease-in-out;
	-o-transition: opacity 0.5s ease-in-out;
	transition: opacity 0.5s ease-in-out;
	opacity:1;
	-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";
}
.desktop .theme_img {
	padding: 10px 0 15px;
}
.desktop .theme_name {
	font: 12px/16px 'Oswald', sans-serif;
	text-transform:uppercase;
}
.desktop:hover {
	background: url(../img/desktop.png) no-repeat 0 right;
}


text:
package view_inspector.ui.dialog;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.TypedValue;
import android.view.ContextThemeWrapper;
import com.f2prateek.rx.preferences.Preference;
import javax.inject.Inject;
import view_inspector.R;
import view_inspector.ViewInspector;
import view_inspector.dagger.qualifier.BypassInterceptor;
import view_inspector.ui.ViewInspectorToolbar;
import view_inspector.ui.menu.BaseMenu;

public class BaseDialog extends AlertDialog {
  @Inject @BypassInterceptor Preference<Boolean> bypassInterceptor;
  @Inject ViewInspectorToolbar toolbar;
  BaseMenu mMenu;

  public BaseDialog(Context context) {
    super(context);
    ViewInspector.runtimeComponentMap.get(((ContextThemeWrapper) context).getBaseContext())
        .inject(this);
    setCancelable(true);
    setCanceledOnTouchOutside(true);
    setOnCancelListener(new OnCancelListener() {
      @Override public void onCancel(DialogInterface dialog) {
        restoreOpenedMenu();
      }
    });
  }

  @Override public void onAttachedToWindow() {
    bypassInterceptor.set(true);
    mMenu = toolbar.getMenu();
    toolbar.closeToolbar();
    super.onAttachedToWindow();
  }

  @Override public void onDetachedFromWindow() {
    bypassInterceptor.set(false);
    super.onDetachedFromWindow();
  }

  protected void restoreOpenedMenu() {
    toolbar.toggleToolbar();
    if (mMenu != null) toolbar.openMenu(mMenu);
  }

  public static int getDialogTheme(Context context) {
    TypedValue outValue = new TypedValue();
    context.getTheme().resolveAttribute(R.attr.isLightTheme, outValue, true);
    return outValue.data != 0 ? R.style.DialogThemeLight : R.style.DialogTheme;
  }
}


text:
<?php

/* MMMBlogBundle:Blog:voir.html.twig */
class __TwigTemplate_541ba709ed81d5d7078c0147243ef27f extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        // line 2
        echo "
<!DOCTYPE html>

    <title>Bienvenue sur ma première page avec le Site du Zéro !</title>

Lecture d'un article

      ";
        // line 13
        echo "      ";
        $context['_parent'] = (array) $context;
        $context['_seq'] = twig_ensure_traversable($this->getAttribute($this->getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : $this->getContext($context, "app")), "session"), "flashbag"), "get", array(0 => "info"), "method"));
        foreach ($context['_seq'] as $context["_key"] => $context["message"]) {
            // line 14
            echo "
";
            echo twig_escape_filter($this->env, (isset($context["message"]) ? $context["message"] : $this->getContext($context, "message")), "html", null, true);
            echo "

      ";
        }
        $_parent = $context['_parent'];
        unset($context['_seq'], $context['_iterated'], $context['_key'], $context['message'], $context['_parent'], $context['loop']);
        $context = array_intersect_key($context, $_parent) + $_parent;
        // line 16
        echo "

      Ici nous pourrons lire l'article ayant comme id : ";
        // line 19
        echo twig_escape_filter($this->env, (isset($context["id"]) ? $context["id"] : $this->getContext($context, "id")), "html", null, true);
        echo "

      Mais pour l'instant, nous ne savons pas encore le faire, cela viendra !

";
    }

    public function getTemplateName()
    {
        return "MMMBlogBundle:Blog:voir.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  50 => 19,  45 => 16,  36 => 14,  31 => 13,  19 => 2,);
    }
}


text:
<!DOCTYPE html>

	<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
	<meta charset="utf-8">

	<link rel="icon" href="favicon.png?v=3" type="image/x-icon">

	<title>foodunites.us</title>
	<link rel="stylesheet" href="bower_components/font-awesome/css/font-awesome.min.css">
	<link rel="stylesheet" href="bower_components/flag-icon-css/css/flag-icon.min.css">
	<link rel="stylesheet" href="css/app.css">

			<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
				Toggle navigation

			</button>

 Home

						3

 Profile

 Share

 About

 Language

Action

Another action

Something else here

Separated link

One more separated link

			<form class="navbar-form navbar-left">

						<input type="text" class="form-control" placeholder="Find your favorite food">

			</form>

	<ng-view></ng-view>


text:
'use strict';
/**
 * Created by yadongw on 15-5-6.
 */

angular.module('webappApp')

    .factory('AuthService', function ($http, Session, API_BASE_URL) {
        var authService = {};

        authService.login = function (email, password) {
            return $http.get(API_BASE_URL + '/user/access-token?email=' + email + '&password=' + password);
        };

        authService.signUp = function (email, password) {
            return $http.post(API_BASE_URL + '/user', {email: email, password: password});
        };

        authService.loginByAccessToken = function (accessToken) {
            return $http.get(API_BASE_URL + '/user/current?access-token=' + accessToken).then(function (res) {
                    return res.data;
                });
        };

        authService.isAuthenticated = function () {
            return !!Session.accessToken;
        };

        authService.saveAccessToken = function (accessToken){
            Session.create(accessToken);
        };

        return authService;
    });


text:
{# Order edit page. #}

{% extends "base.html" %}

{% block head_title %}
Edit order
'{{ order.get('title') or order['_id'] }}'
{% end %}

{% block body_title %}
Edit order
'{{ order.get('title') or order['_id'] }}'
{% end %}

{% block main_content %}
<form action="{{ reverse_url('order_edit', order['_id']) }}"
      role="form"
      method="POST">
  {% module xsrf_form_html() %}

	Title
	<input type="text" class="form-control"
	       name="__title__" id="__title__"
	       value="{{ order.get('title') or '' }}">

      Brief, descriptive title for the order. It is not required to
      be unique, but it is a good idea to make it so anyway.

	Owner
	{% if is_admin %}
	<input type="text" class="form-control"
	       name="__owner__" id="__owner__"
	       value="{{ order['owner'] }}">
	{% else %}
	<select class="form-control" name="__owner__" id="__owner__">
	  {% for colleague in colleagues %}
	    {% set sel = colleague == current_user['email'] and 'selected' or '' %}
	    <option {{ sel }}>{{ colleague }}</option>
	  {% end %}
	</select>
	{% end %}

      {% if is_admin %}
      The order's owner specified by email address. May be changed to
      another account.
      {% else %}
      The order's owner may be changed to an account in your groups.
      NOTE:
      You will then no longer be able to edit the order.
      {% end %}

  {# Recursion: 'include' cannot be used! #}
  {% module Template('order_edit_fields.html', fields=fields, order=order, is_staff=is_staff) %}

{#
  {% set stack = [0] %}
  {% for field in fields %}
    {% while field['depth'] < stack[-1] %}
      {% set stack.pop() %}

    {% end %}
    {% if field['restrict_read'] and not is_staff %}
    {% continue %}
    {% end %}
    {% if field['type'] == constants.GROUP %}
      {% set stack.append(field['depth'] + 1) %}

	    {{ field.get('label') or field['identifier'].capitalize() }}

	      {% if field['identifier'] in order['invalid'] %}

		({{ order['invalid'][field['identifier']] }})

	      {% else %}

	      {% end %}
	      {{ field.get('description') or '' }}

    {% else %}

	      {{ field.get('label') or field['identifier'].capitalize() }}
	      {% if field['identifier'] in order['invalid'] %}

		({{ order['invalid'][field['identifier']] }})

	      {% else %}

	      {% end %}

	    <input type="text" class="form-control"
		   name="{{ field['identifier'] }}"
		   id="{{ field['identifier'] }}"
		   value="{{ order['fields'][field['identifier']] or '' }}">
	    {% if field['required'] %}

	    {% end %}

	  {{ field.get('description') or '' }}

    {% end %}
    {% end %}

    {% while stack.pop() %}

    {% end %}
#}

	<button type="submit" name="__save__" value="continue"
		class="btn btn-success glyphicon glyphicon-floppy-disk">
	  Save and continue
	</button>

	<button type="submit"
		class="btn btn-success glyphicon glyphicon-floppy-save">
	  Save and quit
	</button>

</form>

<form action="{{ reverse_url('order', order['_id']) }}"
      role="form"
      method="GET">

    <button type="submit"
	    class="btn btn-default glyphicon glyphicon-remove">
      Cancel
    </button>

</form>

{% end %} {# block main_content #}

{% block header-css %}
<link rel="stylesheet" href="{{ static_url('jquery-ui-themes-1.11.4/themes/smoothness/jquery-ui.min.css') }}">
{% end %}

{% block javascript_code %}

{# This is required for input fields for date. #}

{% end %}


text:
package io.netty.channel.pool;

import io.netty.channel.Channel;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.Promise;

import java.io.Closeable;
import java.io.IOException;

/**
 * Allows to acquire and release {@link Channel} and so act as a pool of these.
 */
public interface ChannelPool extends Closeable {

    /**
     * Acquire a {@link Channel} from this {@link ChannelPool}. The returned {@link Future} is notified once
     * the acquire is successful and failed otherwise.
     */
    Future<Channel> acquire();

    /**
     * Acquire a {@link Channel} from this {@link ChannelPool}. The given {@link Promise} is notified once
     * the acquire is successful and failed otherwise.
     */
    Future<Channel> acquire(Promise<Channel> promise);

    /**
     * Release a {@link Channel} back to this {@link ChannelPool}. The returned {@link Future} is notified once
     * the release is successful and failed otherwise. When failed the {@link Channel} will automatically closed.
     */
    Future<Void> release(Channel channel);

    /**
     * Release a {@link Channel} back to this {@link ChannelPool}. The given {@link Promise} is notified once
     * the release is successful and failed otherwise. When failed the {@link Channel} will automatically closed.
     */
    Future<Void> release(Channel channel, Promise<Void> promise);

    @Override
    void close();
}


text:
package es_project

import (
	"errors"
	"github.com/watermint/toolbox/essentials/log/esl"
	"io/ioutil"
	"os"
	"path/filepath"
	"runtime"
)

var (
	ErrorUnableToResolveRepositoryRoot = errors.New("unable to resolve repository root")
)

func DetectRepositoryRoot() (string, error) {
	l := esl.Default()
	isRoot := func(p string) bool {
		ll := l.With(esl.String("path", p))
		rootFiles := map[string]bool{
			"tbx.go":    false,
			"README.md": false,
		}
		entries, err := ioutil.ReadDir(p)
		if err != nil {
			ll.Debug("unable to read directory", esl.Error(err))
			return false
		}
		for _, entry := range entries {
			if _, ok := rootFiles[entry.Name()]; ok {
				rootFiles[entry.Name()] = true
			}
		}
		for _, t := range rootFiles {
			if !t {
				return false
			}
		}
		return true
	}
	traverse := func(p string) (q string, err2 error) {
		for {
			if isRoot(p) {
				return p, nil
			}
			p = filepath.ToSlash(filepath.Dir(p))
			if len(p) <= 1 {
				return "", ErrorUnableToResolveRepositoryRoot
			}
		}
	}

	wd, err := os.Getwd()
	if err != nil {
		_, file, _, _ := runtime.Caller(0)
		if p, err := traverse(file); err == nil {
			return p, nil
		}
	} else {
		if p, err := traverse(wd); err == nil {
			return p, nil
		}
	}

	l.Debug("unable to retrieve working directory", esl.Error(err))
	return "", ErrorUnableToResolveRepositoryRoot
}


text:
package org.springframework.web.reactive.result.method.annotation;

import java.util.Map;

import org.springframework.core.MethodParameter;
import org.springframework.core.ReactiveAdapterRegistry;
import org.springframework.ui.Model;
import org.springframework.web.reactive.BindingContext;
import org.springframework.web.reactive.result.method.HandlerMethodArgumentResolverSupport;
import org.springframework.web.reactive.result.method.SyncHandlerMethodArgumentResolver;
import org.springframework.web.server.ServerWebExchange;

/**
 * Resolver for a controller method argument of type {@link Model} that can
 * also be resolved as a {@link java.util.Map}.
 *
 * <p>A Map return value can be interpreted in more than one way depending
 * on the presence of annotations like {@code @ModelAttribute} or
 * {@code @ResponseBody}. As of 5.2 this resolver returns false if a
 * parameter of type {@code Map} is also annotated.
 *
 * @author Rossen Stoyanchev
 * @since 5.2
 */
public class ModelMethodArgumentResolver extends HandlerMethodArgumentResolverSupport
		implements SyncHandlerMethodArgumentResolver {

	public ModelMethodArgumentResolver(ReactiveAdapterRegistry adapterRegistry) {
		super(adapterRegistry);
	}

	@Override
	public boolean supportsParameter(MethodParameter param) {
		return checkParameterTypeNoReactiveWrapper(param, type ->
				Model.class.isAssignableFrom(type) ||
						(Map.class.isAssignableFrom(type) && param.getParameterAnnotations().length == 0));
	}

	@Override
	public Object resolveArgumentValue(
			MethodParameter parameter, BindingContext context, ServerWebExchange exchange) {

		Class<?> type = parameter.getParameterType();
		if (Model.class.isAssignableFrom(type)) {
			return context.getModel();
		}
		else if (Map.class.isAssignableFrom(type)) {
			return context.getModel().asMap();
		}
		else {
			// Should never happen..
			throw new IllegalStateException("Unexpected method parameter type: " + type);
		}
	}

}


text:
% Copyright 2017 Google Inc.
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
%      http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.

function dH = SoftmaxBackward(dP, meta)
% Takes a gradient with respect to P (the output of SoftmaxForward) and
% backpropagates it onto H (the input to SoftmaxForward) using the metadata
% returned by SoftmaxForward.

d_expH = bsxfun(@rdivide, dP, meta.expH_sum);
d_sum = d_expH .* meta.P;
for dim = meta.dims
  d_sum = sum(d_sum, dim);
end
d_sum = full(d_sum);
dH = bsxfun(@minus, d_expH, d_sum) .* meta.expH;


text:
<?php

namespace Bit2Bit\MainBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class NewUserType extends AbstractType {

    public function buildForm(FormBuilderInterface $builder, array $options) {

        $builder
                ->add('email', null, array(
                    'label' => 'E-mail',
                    'required' => true
                ))
                ->add('submit', 'submit', array(
                    'label' => 'Wyślij'
                ))
        ;
    }

    /**
     * Metoda buduje widok formularza.
     *
     * @param FormView $view
     * @param FormInterface $form
     * @param array $options
     */
    public function buildView(FormView $view, FormInterface $form, array $options) {
        parent::buildView($view, $form, $options);
    }

    /**
     * Metoda dodaje do FormBuilder'a opcje możliwe do zdefiniowania podczas
     * tworzenia formularza.
     *
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver) {
        $resolver->setDefaults(array(
            'csrf_protection' => true,
            'data_class' => 'Bit2Bit\MainBundle\Entity\User'
        ));
    }

    /**
     * Metoda zwraca nazwę formularza.
     *
     * @return string
     */
    public function getName() {
        return 'new_user';
    }

}


text:
<!-- omit in toc -->
# Contributing to Vivid Vector Alphabet

First off, thanks for taking the time to contribute! 👁

All types of contributions are encouraged and valued. See the [Table of Contents](#table-of-contents) for different ways to help and details about how this project handles them. Please make sure to read the relevant section before making your contribution. It will make it a lot easier for us maintainers and smooth out the experience for all involved. The community looks forward to your contributions. 🍭

> And if you like the project, but just don't have time to contribute, that's fine. There are other easy ways to support the project and show your appreciation, which we would also be very happy about:
> - Star the project
> - Tweet about it
> - Refer this project in your project's readme
> - Mention the project at local meetups and tell your friends/colleagues 🦄

<!-- omit in TOC -->
## Table of Contents

- [I Have a Question](#i-have-questions)
- [I Want To Contribute](#i-want-to-contribute)
  - [Reporting Bugs](#reporting-bugs)
  - [Suggesting Enhancements](#suggesting-enhancements)
  - [Your First Code Contribution](#your-first-code-contribution)
  - [Improving The Documentation](#improving-the-documentation)
- [Styleguides](#styleguides)
  - [Commit Messages](#commit-messages)
- [Join The Project Team](#join-the-project-team)

## I Have Questions

> If you want to ask a question, we assume that you have read the available [Documentation](https://github.com/neodigm/vivid_vector_alphabet/blob/gh-pages/README.MD).

Before you ask a question, it is best to search for existing [Issues](https://github.com/neodigm/vivid_vector_alphabet/issues) that might help you. In case you have found a suitable issue and still need clarification, you can write your question in this issue. It is also advisable to search the internet for answers first.

If you then still feel the need to ask a question and need clarification, we recommend the following:

- Open an [Issue](https://github.com/neodigm/vivid_vector_alphabet/issues/new).
- Provide as much context as you can about what you're running into.
- Provide project and platform versions (nodejs, npm, etc), depending on what seems relevant. 🦄

We will then take care of the issue as soon as possible.

<!--
You might want to create a separate issue tag for questions and include it in this description. People should then tag their issues accordingly.

Depending on how large the project is, you may want to outsource the questioning, e.g. to Stack Overflow or Gitter. You may add additional contact and information possibilities:
- IRC
- Slack
- Gitter
- Stack Overflow tag
- Blog
- FAQ
- Roadmap
- E-Mail List
- Forum
-->

## I Want To Contribute

> ### Legal Notice <!-- omit in toc -->
> When contributing to this project, you must agree that you have authored 100% of the content, that you have the necessary rights to the content and that the content you contribute may be provided under the project license.

### Reporting Bugs

<!-- omit in toc -->
#### Before Submitting a Bug Report

A good bug report shouldn't leave others needing to chase you up for more information. Therefore, we ask you to investigate carefully, collect information and describe the issue in detail in your report. Please complete the following steps in advance to help us fix any potential bug as fast as possible.

- Make sure that you are using the latest version.
- Determine if your bug is really a bug and not an error on your side e.g. using incompatible environment components/versions (Make sure that you have read the [documentation](https://github.com/neodigm/vivid_vector_alphabet/readme.md). If you are looking for support, you might want to check [this section](#i-have-a-question)).
- To see if other users have experienced (and potentially already solved) the same issue you are having, check if there is not already a bug report existing for your bug or error in the [bug tracker](https://github.com/neodigm/vivid_vector_alphabetissues?q=label%3Abug).
- Also make sure to search the internet (including Stack Overflow) to see if users outside of the GitHub community have discussed the issue.
- Collect information about the bug:
  - Stack trace (Traceback)
  - OS, Platform and Version (Windows, Linux, macOS, x86, ARM)
  - Version of the interpreter, compiler, SDK, runtime environment, package manager, depending on what seems relevant.
  - Possibly your input and the output
  - Can you reliably reproduce the issue? And can you also reproduce it with older versions?

<!-- omit in toc -->
#### How Do I Submit a Good Bug Report?

> You must never report security related issues, vulnerabilities or bugs to the issue tracker, or elsewhere in public. Instead sensitive bugs must be sent by email to <neodigm.ux@gmail.com>.
<!-- You may add a PGP key to allow the messages to be sent encrypted as well. -->

We use GitHub issues to track bugs and errors. If you run into an issue with the project:

- Open an [Issue](https://github.com/neodigm/vivid_vector_alphabetissues/new). (Since we can't be sure at this point whether it is a bug or not, we ask you not to talk about a bug yet and not to label the issue.)
- Explain the behavior you would expect and the actual behavior.
- Please provide as much context as possible and describe the *reproduction steps* that someone else can follow to recreate the issue on their own. This usually includes your code. For good bug reports you should isolate the problem and create a reduced test case.
- Provide the information you collected in the previous section.

Once it's filed:

- The project team will label the issue accordingly.
- A team member will try to reproduce the issue with your provided steps. If there are no reproduction steps or no obvious way to reproduce the issue, the team will ask you for those steps and mark the issue as `needs-repro`. Bugs with the `needs-repro` tag will not be addressed until they are reproduced.
- If the team is able to reproduce the issue, it will be marked `needs-fix`, as well as possibly other tags (such as `critical`), and the issue will be left to be [implemented by someone](#your-first-code-contribution).

<!-- You might want to create an issue template for bugs and errors that can be used as a guide and that defines the structure of the information to be included. If you do so, reference it here in the description. -->

### Suggesting Enhancements

This section guides you through submitting an enhancement suggestion for Vivid Vector Alphabet, **including completely new features and minor improvements to existing functionality**. Following these guidelines will help maintainers and the community to understand your suggestion and find related suggestions.

<!-- omit in toc -->
#### Before Submitting an Enhancement

- Make sure that you are using the latest version.
- Read the [documentation](https://github.com/neodigm/vivid_vector_alphabet/readme.md) carefully and find out if the functionality is already covered, maybe by an individual configuration.
- Perform a [search](https://github.com/neodigm/vivid_vector_alphabetissues) to see if the enhancement has already been suggested. If it has, add a comment to the existing issue instead of opening a new one.
- Find out whether your idea fits with the scope and aims of the project. It's up to you to make a strong case to convince the project's developers of the merits of this feature. Keep in mind that we want features that will be useful to the majority of our users and not just a small subset. If you're just targeting a minority of users, consider writing an add-on/plugin library.

<!-- omit in toc -->
#### How Do I Submit a Good Enhancement Suggestion?

Enhancement suggestions are tracked as [GitHub issues](https://github.com/neodigm/vivid_vector_alphabetissues).

- Use a **clear and descriptive title** for the issue to identify the suggestion.
- Provide a **step-by-step description of the suggested enhancement** in as many details as possible.
- **Describe the current behavior** and **explain which behavior you expected to see instead** and why. At this point you can also tell which alternatives do not work for you.
- You may want to **include screenshots and animated GIFs** which help you demonstrate the steps or point out the part which the suggestion is related to. You can use [this tool](https://www.cockos.com/licecap/) to record GIFs on macOS and Windows, and [this tool](https://github.com/colinkeenan/silentcast) or [this tool](https://github.com/GNOME/byzanz) on Linux. <!-- this should only be included if the project has a GUI -->
- **Explain why this enhancement would be useful** to most Vivid Vector Alphabet users. You may also want to point out the other projects that solved it better and which could serve as inspiration.

<!-- You might want to create an issue template for enhancement suggestions that can be used as a guide and that defines the structure of the information to be included. If you do so, reference it here in the description. -->

### Your First Code Contribution
<!-- TODO
include Setup of env, IDE and typical getting started instructions?

-->

### Improving The Documentation
<!-- TODO
Updating, improving and correcting the documentation

-->

## Styleguides
### Commit Messages
<!-- TADA

-->

## Join The Project Team
<!-- TODO -->

<!-- omit in toc -->
## Attribution
This guide is based on the **contributing-gen**. [Make your own](https://github.com/bttger/contributing-gen)!


text:
package dns

import "gopkg.in/ns1/ns1-go.v2/rest/model/data"

// Zone wraps an NS1 /zone resource
type Zone struct {
	// Zones have metadata tables, but no filters act on 'zone-level' meta.
	Meta *data.Meta `json:"meta,omitempty"`

	// Read-only fields
	DNSServers   []string `json:"dns_servers,omitempty"`
	NetworkPools []string `json:"network_pools,omitempty"`
	Pool         string   `json:"pool,omitempty"` // Deprecated

	ID   string `json:"id,omitempty"`
	Zone string `json:"zone,omitempty"`

	TTL        int    `json:"ttl,omitempty"`
	NxTTL      int    `json:"nx_ttl,omitempty"`
	Retry      int    `json:"retry,omitempty"`
	Serial     int    `json:"serial,omitempty"`
	Refresh    int    `json:"refresh,omitempty"`
	Expiry     int    `json:"expiry,omitempty"`
	Hostmaster string `json:"hostmaster,omitempty"`

	// If this is a linked zone, Link points to an existing standard zone,
	// reusing its configuration and records. Link is a zones' domain name.
	Link *string `json:"link,omitempty"`

	// Networks contains the network ids the zone is available. Most zones
	// will be in the NSONE Global Network(which is id 0).
	NetworkIDs []int         `json:"networks,omitempty"`
	Records    []*ZoneRecord `json:"records,omitempty"`

	// Primary contains info to enable slaving of the zone by third party dns servers.
	Primary *ZonePrimary `json:"primary,omitempty"`
	// Secondary contains info for slaving the zone to a primary dns server.
	Secondary *ZoneSecondary `json:"secondary,omitempty"`
}

func (z Zone) String() string {
	return z.Zone
}

// ZoneRecord wraps Zone's "records" attribute
type ZoneRecord struct {
	Domain   string   `json:"Domain,omitempty"`
	ID       string   `json:"id,omitempty"`
	Link     string   `json:"link,omitempty"`
	ShortAns []string `json:"short_answers,omitempty"`
	Tier     int      `json:"tier,omitempty"`
	TTL      int      `json:"ttl,omitempty"`
	Type     string   `json:"type,omitempty"`
}

// ZonePrimary wraps a Zone's "primary" attribute
type ZonePrimary struct {
	// Enabled determines whether AXFR queries (and optionally NOTIFY messages)
	// will be enabled for the zone.
	Enabled     bool                  `json:"enabled"`
	Secondaries []ZoneSecondaryServer `json:"secondaries"`
}

// ZoneSecondaryServer wraps elements of a Zone's "primary.secondary" attribute
type ZoneSecondaryServer struct {
	// Read-Only
	NetworkIDs []int `json:"networks,omitempty"`

	IP     string `json:"ip"`
	Port   int    `json:"port,omitempty"`
	Notify bool   `json:"notify"`
}

// ZoneSecondary wraps a Zone's "secondary" attribute
type ZoneSecondary struct {
	// Read-Only fields
	Expired bool    `json:"expired,omitempty"`
	LastXfr int     `json:"last_xfr,omitempty"`
	Status  string  `json:"status,omitempty"`
	Error   *string `json:"error"`

	PrimaryIP   string `json:"primary_ip,omitempty"`
	PrimaryPort int    `json:"primary_port,omitempty"`
	Enabled     bool   `json:"enabled"`

	TSIG *TSIG `json:"tsig"`
}

// TSIG is a zones transaction signature.
type TSIG struct {
	// Key is the encrypted TSIG key(read-only)
	Key string `json:"key,omitempty"`

	// Whether TSIG is enabled for a secondary zone.
	Enabled bool `json:"enabled,omitempty"`
	// Which hashing algorithm
	Hash string `json:"hash,omitempty"`
	// Name of the TSIG key
	Name string `json:"name,omitempty"`
}

// NewZone takes a zone domain name and creates a new zone.
func NewZone(zone string) *Zone {
	z := Zone{
		Zone: zone,
	}
	return &z
}

// MakePrimary enables Primary, disables Secondary, and sets primary's
// Secondaries to all provided ZoneSecondaryServers
func (z *Zone) MakePrimary(secondaries ...ZoneSecondaryServer) {
	z.Secondary = nil
	z.Primary = &ZonePrimary{
		Enabled:     true,
		Secondaries: secondaries,
	}
	if z.Primary.Secondaries == nil {
		z.Primary.Secondaries = make([]ZoneSecondaryServer, 0)
	}
}

// MakeSecondary enables Secondary, disables Primary, and sets secondary's
// Primary_ip to provided ip.
func (z *Zone) MakeSecondary(ip string) {
	z.Secondary = &ZoneSecondary{
		Enabled:     true,
		PrimaryIP:   ip,
		PrimaryPort: 53,
	}
	z.Primary = &ZonePrimary{
		Enabled:     false,
		Secondaries: make([]ZoneSecondaryServer, 0),
	}
}

// LinkTo sets Link to a target zone domain name and unsets all other configuration properties.
// No other zone configuration properties (such as refresh, retry, etc) may be specified,
// since they are all pulled from the target zone. Linked zones, once created, cannot be
// configured at all and cannot have records added to them. They may only be deleted, which
// does not affect the target zone at all.
func (z *Zone) LinkTo(to string) {
	z.Meta = nil
	z.TTL = 0
	z.NxTTL = 0
	z.Retry = 0
	z.Refresh = 0
	z.Expiry = 0
	z.Primary = nil
	z.DNSServers = nil
	z.NetworkIDs = nil
	z.NetworkPools = nil
	z.Hostmaster = ""
	z.Pool = ""
	z.Secondary = nil
	z.Link = &to
}


text:
<?php

abstract class BL_CustomGrid_Block_Column_Renderer_Collection_Abstract extends Mage_Adminhtml_Block_Template
{
    protected function _getAvailableRenderers()
    {
        return Mage::getSingleton('customgrid/column_renderer_config_collection')->getRenderersArray();
    }

    protected function _getAvailableRenderer($code)
    {
        $renderers = $this->_getAvailableRenderers();
        return (isset($renderers[$code]) ? $renderers[$code] : null);
    }
}


text:
package org.apache.activemq.bugs;

import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.Topic;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.EmbeddedBrokerTestSupport;
import org.apache.activemq.broker.BrokerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ConnectionPerMessageTest extends EmbeddedBrokerTestSupport {

   private static final Logger LOG = LoggerFactory.getLogger(ConnectionPerMessageTest.class);
   private static final int COUNT = 2000;
   protected String bindAddress;

   public void testConnectionPerMessage() throws Exception {
      final String topicName = "test.topic";

      LOG.info("Initializing connection factory for JMS to URL: " + bindAddress);
      final ActiveMQConnectionFactory normalFactory = new ActiveMQConnectionFactory();
      normalFactory.setBrokerURL(bindAddress);
      for (int i = 0; i < COUNT; i++) {

         if (i % 100 == 0) {
            LOG.info(new Integer(i).toString());
         }

         Connection conn = null;
         try {

            conn = normalFactory.createConnection();
            final Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
            final Topic topic = session.createTopic(topicName);
            final MessageProducer producer = session.createProducer(topic);
            producer.setDeliveryMode(DeliveryMode.PERSISTENT);

            final MapMessage m = session.createMapMessage();
            m.setInt("hey", i);

            producer.send(m);

         }
         catch (JMSException e) {
            LOG.warn(e.getMessage(), e);
         }
         finally {
            if (conn != null)
               try {
                  conn.close();
               }
               catch (JMSException e) {
                  LOG.warn(e.getMessage(), e);
               }
         }
      }
   }

   protected void setUp() throws Exception {
      bindAddress = "vm://localhost";
      super.setUp();
   }

   protected BrokerService createBroker() throws Exception {
      BrokerService answer = new BrokerService();
      answer.setDeleteAllMessagesOnStartup(true);
      answer.setUseJmx(false);
      answer.setPersistent(isPersistent());
      answer.addConnector(bindAddress);
      return answer;
   }

   protected boolean isPersistent() {
      return true;
   }

   protected void tearDown() throws Exception {
      super.tearDown();
   }

}


text:
package de.otto.flummi.query;

import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;

import static de.otto.flummi.request.GsonHelper.object;

public class HasParentQueryBuilder implements QueryBuilder {
    private final String type;
    private final QueryBuilder query;

    public HasParentQueryBuilder(String type, QueryBuilder query) {
        this.type = type;
        this.query = query;
    }

    @Override
    public JsonObject build() {
        JsonObject hasParent = new JsonObject();
        hasParent.add("type", new JsonPrimitive(type));
        hasParent.add("query", query.build());
        return object(
                "has_parent",
                hasParent);
    }
}


text:
Set up my OSX for development

[![Build Status](https://travis-ci.org/Leko/setup-osx.svg?branch=master)](https://travis-ci.org/Leko/setup-osx)

## Tested os versions
- `10.10` (Yosemite)

## Getting started
```sh
# Install XCode Command Line Tool
xcode-select --install
sudo xcode-select --switch /Library/Developer/CommandLineTools/

# Install Homebrew
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
brew install ansible
brew doctor

# Clone
cd ~
git clone https://github.com/Leko/setup-osx.git setup-osx
cd setup-osx
echo 'YOUR_USER_PASSWORD' > secret
ansible-playbook localhost.yml -vv -i hosts

# Update
cd ~/setup-osx
ansible-playbook localhost.yml -vv -i hosts
```

## Languages ([anyenv](https://github.com/riywo/anyenv))
List all languages & versions

```
anyenv versions
```

### Ruby ([rbenv](https://github.com/rbenv/rbenv))

```sh
rbenv          # help
rbenv version  # display current Ruby version
rbenv versions # list installed Ruby versions
```

### PHP ([phpenv](https://github.com/phpenv/phpenv))

```sh
phpen           # help
phpenv version  # display current PHP version
phpenv versions # list installed PHP versions
```

### Go ([goenv]())

```sh
goenv          # help
goenv version  # display current Go version
goenv versions # list installed Go versions
```

### Nodejs (ndenv)

```sh
ndenv          # help
ndenv version  # display current Nodejs version
ndenv versions # list installed Nodejs versions
```

## Other

### Brew components
```sh
brew list
```

### Applications
```sh
brew cask list | grep -v font # without fonts
```

### Fonts
```sh
brew cask list | grep font
```


text:
module HerokuBackupOrchestrator
  class HerokuBackup
    # @param [String] application_name The name of the Heroku application that was backed up
    # @param [String] url The (temporary) public_url where the backup file can be accessed
    def initialize(application_name, url)
      @application_name = application_name
      @id = create_id(application_name)
      @url = url
      @type = "pgdump"
    end

    attr_reader :id, :url, :type, :application_name

    private

    def create_id(application_name)
      "heroku_backup_orchestrator/#{application_name}/#{Date.today}.dump"
    end
  end

  class HerokuApplication
    # @param [String] user The username required to log in to the application
    # @param [String] password The password required to log into the application
    # @param [String] application_name The name of the heroku application
    # @raise [BackupError] A BackupError will be raised if the pgbackups addon is not added to the application
    def initialize(user, password, application_name)
      @application_name = application_name
      heroku = Heroku::Client.new(user, password)
      config_vars = heroku.config_vars(application_name)
      @from_name = 'DATABASE_URL'
      @from_url = config_vars[@from_name]
      authenticated_url = config_vars['PGBACKUPS_URL']
      raise BackupError, 'Please add the (free) PGBackups addon before using Heroku Backup Orchestrator with your application' unless authenticated_url
      @client = PGBackups::Client.new(authenticated_url)
    end

    def self.application_names
      CONFIG['heroku'].keys
    end

    def self.find_by_name(name)
      CONFIG['heroku'].each_key do |app|
        return HerokuApplication.new(CONFIG['heroku'][app]['user'], CONFIG['heroku'][app]['password'], app) if name == app
      end
      nil
    end

    def self.all
      apps = []
      CONFIG['heroku'].each do |app, config|
        apps << HerokuApplication.new(CONFIG['heroku'][app]['user'], CONFIG['heroku'][app]['password'], app)
      end
      apps
    end

    # Creates a new backup (pgdump) of a Heroku application.
    # Will expire the exiting backup (same as --expire from the heroku command line tool).
    #
    # @raise [BackupError] A BackupError will be raised if the backup fails for some reason
    # @return [HerokuBackup] The newly created backup
    def create_backup
      backup = @client.create_transfer(@from_url, @from_name, nil, 'BACKUP', :expire => true)
      raise BackupError, 'Heroku indicated something went wrong with the backup. Please investigate.' if backup['errors']
      while true
        break if backup['finished_at']
        sleep 5
        backup = @client.get_transfer(backup['id'])
      end
      HerokuBackup.new(@application_name, backup['public_url'])
    end

    def to_s
      @application_name
    end
  end
end


text:
package com.ctrip.framework.xpipe.redis.servlet.spring;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.env.Environment;

import javax.servlet.DispatcherType;
import javax.servlet.ServletException;

@Configuration
public class AutoConfiguration {

    @Configuration
    static class ConfigurationNew {

        @Autowired
        Environment environment;

        @Bean(name = "ProxyFilterRegistrationBeanNew")
        public org.springframework.boot.web.servlet.FilterRegistrationBean factory() throws ServletException {
            org.springframework.boot.web.servlet.FilterRegistrationBean filter =
                    new org.springframework.boot.web.servlet.FilterRegistrationBean();
            initFilter(filter);
            return filter;
        }
    }

    private static void initFilter(FilterRegistrationBean filter) throws ServletException {
        filter.setFilter(new ProxyFilter());
        filter.setName("proxy-filter");
        filter.addUrlPatterns("/proxy/client");
        filter.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.FORWARD);
        filter.setAsyncSupported(true);
        filter.setOrder(Ordered.HIGHEST_PRECEDENCE);
    }

}


text:
class Auth::Workflow::Consumable
	include Mongoid::Document
	embedded_in :minute, :class_name => Auth.configuration.minute_class
	field :product_id, type: String
	field :quantity, type: Float
	attr_accessor :minute_requirement
end


text:
=begin
  locale.rb - Locale module

  Copyright (C) 2002-2007  Masao Mutoh

  You may redistribute it and/or modify it under the same
  license terms as Ruby.

  $Id: locale.rb,v 1.2 2007/11/08 16:44:22 mutoh Exp $
=end

require 'locale/object'

if /cygwin|mingw|win32/ =~ RUBY_PLATFORM
  require 'locale/win32'
elsif /java/ =~ RUBY_PLATFORM
  require 'locale/jruby'
else
  require 'locale/posix'
end

# Locale module manages the locale informations of the application.
module Locale
  @@default = nil
  @@current = nil

  module_function
  # Sets the default locale (Locale::Object or String(such as ja_JP.eucJP)).
  #
  # * locale: the default locale
  # * Returns: self.
  def set_default(locale)
    if locale
      if locale.kind_of? Locale::Object
        @@default = locale
      else
        @@default = Locale::Object.new(locale)
      end
      @@default.charset ||= @@locale_system_module.charset
    else
      @@default = nil
    end
    self
  end
  # Same as Locale.set_default.
  #
  # * locale: the default locale (Locale::Object).
  # * Returns: locale.
  def default=(locale)
    set_default(locale)
    @@default
  end

  # Gets the system locale.
  # * Returns: the system locale (Locale::Object).
  def system
    @@locale_system_module.system
  end

  # Gets the default locale.
  #
  # If the default locale not set, this returns system locale.
  # * Returns: the default locale (Locale::Object).
  def default
    @@default ? @@default : system
  end

  # Gets the current locale (Locale::Object).
  #
  # If the current locale is not set, this returns default locale.
  # * Returns: the current locale (Locale::Object).
  def current
    @@current = default unless @@current
    @@current
  end

  # Sets a locale as the current locale.
  #
  # This returns the current Locale::Object.
  # * lang: Locale::Object or locale name(String), or language name.
  # * country: the country code(String)
  # * charset: the charset(override the charset even if the locale name has charset).
  # * Returns: self
  #
  #    Locale.set_current("ja_JP.eucJP")
  #    Locale.set_current("ja", "JP")
  #    Locale.set_current("ja", "JP", "eucJP")
  #    Locale.set_current("ja", nil, "eucJP")
  #    Locale.set_current(Locale::Object.new("ja", "JP", "eucJP"))
  def set_current(lang, country = nil, charset = nil)
    if lang == nil
      @@current = nil
    else
      if lang.kind_of? Locale::Object
	@@current = lang
      else
	@@current = Locale::Object.new(lang, country, charset)
      end
      @@current.charset ||= @@locale_system_module.charset
    end
    self
  end

  # Sets a current locale. This is a single argument version of Locale.set_current.
  #
  # * lang: the Locale::Object
  # * Returns: the current locale (Locale::Object).
  #
  #    Locale.current = "ja_JP.eucJP"
  #    Locale.current = Locale::Object.new("ja", "JP", "eucJP")
  def current=(lang)
    set_current(lang)
    @@current
  end

  # call-seq:
  #   set(lang)
  #   set(lang, country = nil, charset = nil)
  #
  # * lang: language as String, or Locale::Object
  # * country: country as String or nil
  # * charset: charset as String or nil
  # * Returns: a Locale::Object.
  #
  # Sets a default locale. This function is an alias of Locale.set_default with
  # calling set_current(nil).
  #
  # *Notice*: Locale.set(lctype, locale) is deprecated.
  def set(lang, country = nil, charset = nil)
    set_current(nil)
    if lang.kind_of? String
      set_default(Locale::Object.new(lang, country, charset))
    elsif lang.kind_of? Locale::Object
      set_default(lang)
    else
      set_default(nil)
    end
    @@default
  end

  # call-seq:
  #   current
  #   get
  #
  # * Returns: the current locale (Locale::Object).
  #
  # *Notice*: lctype is deprecated. Use this with no parameter instead.
  def get
    @@current = default unless @@current
    @@current
  end

  # Same as charset. Gets the charset of the current locale.
  # * Returns: the charset of the current locale (String)
  def codeset
    current.charset
  end

  # Gets the charset of the current locale.
  # * Returns: the charset of the current locale (String)
  def charset
    codeset
  end
  # Same as codeset. Returns the charset of the current locale.
  # * Returns: the charset of the current locale (String)
  def current_charset
    codeset
  end

  # Clear default/current locale.
  # * Returns: self
  def clear
    set(nil)
    set_current(nil)
    self
  end

  # Gets the current system module. This is used for debugging.
  # * Returns: the system module.
  def system_module
    @@locale_system_module
  end
end