code
stringlengths
2
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
991
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Copyright (c) 2011-2013 The PPCoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "checkpoints.h" #include "db.h" #include "net.h" #include "init.h" #include "ui_interface.h" #include "kernel.h" #include "main.h" #include <boost/algorithm/string/replace.hpp> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <cstdlib> #include "GetNextTargetRequired.h" #include "GetProofOfStakeReward.h" #include "GetProofOfWorkReward.h" using namespace std; using namespace boost; // // Global state // CCriticalSection cs_setpwalletRegistered; set<CWallet*> setpwalletRegistered; CCriticalSection cs_main; CTxMemPool mempool; unsigned int nTransactionsUpdated = 0; map<uint256, CBlockIndex*> mapBlockIndex; set<pair<COutPoint, unsigned int> > setStakeSeen; CBlockIndex* pindexGenesisBlock = NULL; int nBestHeight = -1; CBigNum bnBestChainTrust = 0; CBigNum bnBestInvalidTrust = 0; uint256 hashBestChain = 0; CBlockIndex* pindexBest = NULL; int64 nTimeBestReceived = 0; CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have map<uint256, CBlock*> mapOrphanBlocks; multimap<uint256, CBlock*> mapOrphanBlocksByPrev; set<pair<COutPoint, unsigned int> > setStakeSeenOrphan; map<uint256, uint256> mapProofOfStake; map<uint256, CDataStream*> mapOrphanTransactions; map<uint256, map<uint256, CDataStream*> > mapOrphanTransactionsByPrev; // Constant stuff for coinbase transactions we create: CScript COINBASE_FLAGS; const string strMessageMagic = COIN_NAME " Signed Message:\n"; double dHashesPerSec; int64 nHPSTimerStart; // Settings int64 nTransactionFee = MIN_TX_FEES; ////////////////////////////////////////////////////////////////////////////// // // dispatching functions // // These functions dispatch to one or all registered wallets void RegisterWallet(CWallet* pwalletIn) { { LOCK(cs_setpwalletRegistered); setpwalletRegistered.insert(pwalletIn); } } void UnregisterWallet(CWallet* pwalletIn) { { LOCK(cs_setpwalletRegistered); setpwalletRegistered.erase(pwalletIn); } } // check whether the passed transaction is from us bool static IsFromMe(CTransaction& tx) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) if (pwallet->IsFromMe(tx)) return true; return false; } // get the wallet transaction with the given hash (if it exists) bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) if (pwallet->GetTransaction(hashTx,wtx)) return true; return false; } // erases transaction with the given hash from all wallets void static EraseFromWallets(uint256 hash) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->EraseFromWallet(hash); } // make sure all wallets know about the given transaction, in the given block void SyncWithWallets(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fConnect) { if (!fConnect) { // ppcoin: wallets need to refund inputs when disconnecting coinstake if (tx.IsCoinStake()) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) if (pwallet->IsFromMe(tx)) pwallet->DisableTransaction(tx); } return; } BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate); } // notify wallets about a new best chain void static SetBestChain(const CBlockLocator& loc) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->SetBestChain(loc); } // notify wallets about an updated transaction void static UpdatedTransaction(const uint256& hashTx) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->UpdatedTransaction(hashTx); } // dump all wallets void static PrintWallets(const CBlock& block) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->PrintWallet(block); } // notify wallets about an incoming inventory (for request counts) void static Inventory(const uint256& hash) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->Inventory(hash); } // ask wallets to resend their transactions void static ResendWalletTransactions() { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->ResendWalletTransactions(); } ////////////////////////////////////////////////////////////////////////////// // // mapOrphanTransactions // bool AddOrphanTx(const CDataStream& vMsg) { CTransaction tx; CDataStream(vMsg) >> tx; uint256 hash = tx.GetHash(); if (mapOrphanTransactions.count(hash)) return false; CDataStream* pvMsg = new CDataStream(vMsg); // Ignore big transactions, to avoid a // send-big-orphans memory exhaustion attack. If a peer has a legitimate // large transaction with a missing parent then we assume // it will rebroadcast it later, after the parent transaction(s) // have been mined or received. // 10,000 orphans, each of which is at most 5,000 bytes big is // at most 500 megabytes of orphans: if (pvMsg->size() > 5000) { printf("ignoring large orphan tx (size: %u, hash: %s)\n", pvMsg->size(), hash.ToString().substr(0,10).c_str()); delete pvMsg; return false; } mapOrphanTransactions[hash] = pvMsg; BOOST_FOREACH(const CTxIn& txin, tx.vin) mapOrphanTransactionsByPrev[txin.prevout.hash].insert(make_pair(hash, pvMsg)); printf("stored orphan tx %s (mapsz %u)\n", hash.ToString().substr(0,10).c_str(), mapOrphanTransactions.size()); return true; } void static EraseOrphanTx(uint256 hash) { if (!mapOrphanTransactions.count(hash)) return; const CDataStream* pvMsg = mapOrphanTransactions[hash]; CTransaction tx; CDataStream(*pvMsg) >> tx; BOOST_FOREACH(const CTxIn& txin, tx.vin) { mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash); if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty()) mapOrphanTransactionsByPrev.erase(txin.prevout.hash); } delete pvMsg; mapOrphanTransactions.erase(hash); } unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans) { unsigned int nEvicted = 0; while (mapOrphanTransactions.size() > nMaxOrphans) { // Evict a random orphan: uint256 randomhash = GetRandHash(); map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash); if (it == mapOrphanTransactions.end()) it = mapOrphanTransactions.begin(); EraseOrphanTx(it->first); ++nEvicted; } return nEvicted; } ////////////////////////////////////////////////////////////////////////////// // // CTransaction and CTxIndex // bool CTransaction::ReadFromDisk(CTxDB& txdb, const uint256& hash, CTxIndex& txindexRet) { SetNull(); if (!txdb.ReadTxIndex(hash, txindexRet)) return false; if (!ReadFromDisk(txindexRet.pos)) return false; return true; } bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet) { if (!ReadFromDisk(txdb, prevout.hash, txindexRet)) return false; if (prevout.n >= vout.size()) { SetNull(); return false; } return true; } bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout) { CTxIndex txindex; return ReadFromDisk(txdb, prevout, txindex); } bool CTransaction::ReadFromDisk(COutPoint prevout) { CTxDB txdb("r"); CTxIndex txindex; return ReadFromDisk(txdb, prevout, txindex); } bool CTransaction::IsStandard() const { BOOST_FOREACH(const CTxIn& txin, vin) { // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG // pay-to-script-hash, which is 3 ~80-byte signatures, 3 // ~65-byte public keys, plus a few script ops. if (txin.scriptSig.size() > 500) return false; if (!txin.scriptSig.IsPushOnly()) return false; } unsigned int nDataOut = 0; txnouttype whichType; BOOST_FOREACH(const CTxOut& txout, vout) { if (!::IsStandard(txout.scriptPubKey, whichType)) { return false; } if (whichType == TX_NULL_DATA) nDataOut++; } // only one OP_RETURN txout is permitted if (nDataOut > 1) { return false; } return true; } // // Check transaction inputs, and make sure any // pay-to-script-hash transactions are evaluating IsStandard scripts // // Why bother? To avoid denial-of-service attacks; an attacker // can submit a standard HASH... OP_EQUAL transaction, // which will get accepted into blocks. The redemption // script can be anything; an attacker could use a very // expensive-to-check-upon-redemption script like: // DUP CHECKSIG DROP ... repeated 100 times... OP_1 // bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const { if (IsCoinBase()) return true; // Coinbases don't use vin normally for (unsigned int i = 0; i < vin.size(); i++) { const CTxOut& prev = GetOutputFor(vin[i], mapInputs); vector<vector<unsigned char> > vSolutions; txnouttype whichType; // get the scriptPubKey corresponding to this input: const CScript& prevScript = prev.scriptPubKey; if (!Solver(prevScript, whichType, vSolutions)) return false; int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions); if (nArgsExpected < 0) return false; // Transactions with extra stuff in their scriptSigs are // non-standard. Note that this EvalScript() call will // be quick, because if there are any operations // beside "push data" in the scriptSig the // IsStandard() call returns false vector<vector<unsigned char> > stack; if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0)) return false; if (whichType == TX_SCRIPTHASH) { if (stack.empty()) return false; CScript subscript(stack.back().begin(), stack.back().end()); vector<vector<unsigned char> > vSolutions2; txnouttype whichType2; if (!Solver(subscript, whichType2, vSolutions2)) return false; if (whichType2 == TX_SCRIPTHASH) return false; int tmpExpected; tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2); if (tmpExpected < 0) return false; nArgsExpected += tmpExpected; } if (stack.size() != (unsigned int)nArgsExpected) return false; } return true; } unsigned int CTransaction::GetLegacySigOpCount() const { unsigned int nSigOps = 0; BOOST_FOREACH(const CTxIn& txin, vin) { nSigOps += txin.scriptSig.GetSigOpCount(false); } BOOST_FOREACH(const CTxOut& txout, vout) { nSigOps += txout.scriptPubKey.GetSigOpCount(false); } return nSigOps; } int CMerkleTx::SetMerkleBranch(const CBlock* pblock) { if (fClient) { if (hashBlock == 0) return 0; } else { CBlock blockTmp; if (pblock == NULL) { // Load the block this tx is in CTxIndex txindex; if (!CTxDB("r").ReadTxIndex(GetHash(), txindex)) return 0; if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos)) return 0; pblock = &blockTmp; } // Update the tx's hashBlock hashBlock = pblock->GetHash(); // Locate the transaction for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++) if (pblock->vtx[nIndex] == *(CTransaction*)this) break; if (nIndex == (int)pblock->vtx.size()) { vMerkleBranch.clear(); nIndex = -1; printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n"); return 0; } // Fill in merkle branch vMerkleBranch = pblock->GetMerkleBranch(nIndex); } // Is the tx in a block that's in the main chain map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi == mapBlockIndex.end()) return 0; CBlockIndex* pindex = (*mi).second; if (!pindex || !pindex->IsInMainChain()) return 0; return pindexBest->nHeight - pindex->nHeight + 1; } bool CTransaction::IsRestrictedCoinStake() const { if (!IsCoinStake()) return false; int64 nValueIn = 0; CScript onlyAllowedScript; for (unsigned int i = 0; i < vin.size(); ++i) { const COutPoint& prevout = vin[i].prevout; CTxDB txdb("r"); CTransaction txPrev; CTxIndex txindex; if (!txPrev.ReadFromDisk(txdb, prevout, txindex)) return false; txdb.Close(); const CTxOut& prevtxo = txPrev.vout[prevout.n]; const CScript& prevScript = prevtxo.scriptPubKey; if (i == 0) { onlyAllowedScript = prevScript; if (onlyAllowedScript.empty()) { return false; } } else { if (prevScript != onlyAllowedScript) { return false; } } nValueIn += prevtxo.nValue; } int64 nValueOut = 0; for (unsigned int i = 1; i < vout.size(); ++i) { const CTxOut& txo = vout[i]; if (txo.nValue == 0) continue ; if (txo.scriptPubKey != onlyAllowedScript) return false; nValueOut += txo.nValue; } if (nValueOut < nValueIn) return false; return true; } bool CTransaction::CheckTransaction() const { // Basic checks that don't depend on any context if (vin.empty()) return DoS(10, error("CTransaction::CheckTransaction() : vin empty")); if (vout.empty()) return DoS(10, error("CTransaction::CheckTransaction() : vout empty")); // Time (prevent mempool memory exhaustion attack) if (nTime > GetAdjustedTime() + MAX_CLOCK_DRIFT) return DoS(10, error("CTransaction::CheckTransaction() : timestamp is too far into the future")); // Size limits if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE) return DoS(100, error("CTransaction::CheckTransaction() : size limits failed")); // Check for negative or overflow output values int64 nValueOut = 0; for (size_t i = 0; i < vout.size(); i++) { const CTxOut& txout = vout[i]; if (txout.IsEmpty() && (!IsCoinBase()) && (!IsCoinStake())) return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction")); // ppcoin: enforce minimum output amount if ((!txout.IsEmpty()) && txout.nValue < MIN_TXOUT_AMOUNT) return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue below minimum (%d)", txout.nValue)); if (txout.nValue > MAX_MONEY_STACK) return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high (%d)", txout.nValue)); nValueOut += txout.nValue; if (!IsValidAmount(nValueOut)) return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range")); } // Check for duplicate inputs set<COutPoint> vInOutPoints; BOOST_FOREACH(const CTxIn& txin, vin) { if (vInOutPoints.count(txin.prevout)) return false; vInOutPoints.insert(txin.prevout); } if (IsCoinBase()) { if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100) return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size")); } else { BOOST_FOREACH(const CTxIn& txin, vin) if (txin.prevout.IsNull()) return DoS(10, error("CTransaction::CheckTransaction() : prevout is null")); } return true; } bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs, bool* pfMissingInputs) { if (pfMissingInputs) *pfMissingInputs = false; if (!tx.CheckTransaction()) return error("CTxMemPool::accept() : CheckTransaction failed"); // Coinbase is only valid in a block, not as a loose transaction if (tx.IsCoinBase()) return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx")); // ppcoin: coinstake is also only valid in a block, not as a loose transaction if (tx.IsCoinStake()) return tx.DoS(100, error("CTxMemPool::accept() : coinstake as individual tx")); // To help v0.1.5 clients who would see it as a negative number if ((int64)tx.nLockTime > std::numeric_limits<int>::max()) return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet"); // Rather not work on nonstandard transactions if (!tx.IsStandard()) return error("CTxMemPool::accept() : nonstandard transaction type"); // Do we already have it? uint256 hash = tx.GetHash(); { LOCK(cs); if (mapTx.count(hash)) return false; } if (fCheckInputs) if (txdb.ContainsTx(hash)) return false; // Check for conflicts with in-memory transactions CTransaction* ptxOld = NULL; for (unsigned int i = 0; i < tx.vin.size(); i++) { COutPoint outpoint = tx.vin[i].prevout; if (mapNextTx.count(outpoint)) { // Disable replacement feature for now return false; // Allow replacing with a newer version of the same transaction if (i != 0) return false; ptxOld = mapNextTx[outpoint].ptx; if (ptxOld->IsFinal()) return false; if (!tx.IsNewerThan(*ptxOld)) return false; for (unsigned int i = 0; i < tx.vin.size(); i++) { COutPoint outpoint = tx.vin[i].prevout; if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld) return false; } break; } } if (fCheckInputs) { MapPrevTx mapInputs; map<uint256, CTxIndex> mapUnused; bool fInvalid = false; if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid)) { if (fInvalid) return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str()); if (pfMissingInputs) *pfMissingInputs = true; return error("CTxMemPool::accept() : FetchInputs failed %s", hash.ToString().substr(0,10).c_str()); } // Check for non-standard pay-to-script-hash in inputs if (!tx.AreInputsStandard(mapInputs)) return error("CTxMemPool::accept() : nonstandard transaction input"); // Note: if you modify this code to accept non-standard transactions, then // you should add code here to check that the transaction does a // reasonable number of ECDSA signature verifications. int64 nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut(); unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); // Don't accept it if it can't get into a block if (nFees < tx.GetMinFee(1000, false, GMF_RELAY)) return error("CTxMemPool::accept() : not enough fees"); // Continuously rate-limit free transactions // This mitigates 'penny-flooding' -- sending thousands of free transactions just to // be annoying or make other's transactions take longer to confirm. if (nFees < MIN_RELAY_TX_FEES) { static CCriticalSection cs; static double dFreeCount; static int64 nLastTime; int64 nNow = GetTime(); { LOCK(cs); // Use an exponentially decaying ~10-minute window: dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime)); nLastTime = nNow; // -limitfreerelay unit is thousand-bytes-per-minute // At default rate it would take over a month to fill 1GB if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx)) return error("CTxMemPool::accept() : free transaction rejected by rate limiter"); if (fDebug) printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize); dFreeCount += nSize; } } // Check against previous transactions // This is done last to help prevent CPU exhaustion denial-of-service attacks. if (!tx.ConnectInputs(txdb, mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false)) { return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str()); } } // Store transaction in memory { LOCK(cs); if (ptxOld) { printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str()); remove(*ptxOld); } addUnchecked(tx); } ///// are we sure this is ok when loading transactions or restoring block txes // If updated, erase old tx from wallet if (ptxOld) EraseFromWallets(ptxOld->GetHash()); printf("CTxMemPool::accept() : accepted %s\n", hash.ToString().substr(0,10).c_str()); return true; } bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs) { return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs); } bool CTxMemPool::addUnchecked(CTransaction &tx) { printf("addUnchecked(): size %lu\n", mapTx.size()); // Add to memory pool without checking anything. Don't call this directly, // call CTxMemPool::accept to properly check the transaction first. { LOCK(cs); uint256 hash = tx.GetHash(); mapTx[hash] = tx; for (unsigned int i = 0; i < tx.vin.size(); i++) mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i); nTransactionsUpdated++; } return true; } bool CTxMemPool::remove(CTransaction &tx) { // Remove transaction from memory pool { LOCK(cs); uint256 hash = tx.GetHash(); if (mapTx.count(hash)) { BOOST_FOREACH(const CTxIn& txin, tx.vin) mapNextTx.erase(txin.prevout); mapTx.erase(hash); nTransactionsUpdated++; } } return true; } void CTxMemPool::queryHashes(std::vector<uint256>& vtxid) { vtxid.clear(); LOCK(cs); vtxid.reserve(mapTx.size()); for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi) vtxid.push_back((*mi).first); } int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const { if (hashBlock == 0 || nIndex == -1) return 0; // Find the block it claims to be in map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi == mapBlockIndex.end()) return 0; CBlockIndex* pindex = (*mi).second; if (!pindex || !pindex->IsInMainChain()) return 0; // Make sure the merkle branch connects to this block if (!fMerkleVerified) { if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot) return 0; fMerkleVerified = true; } pindexRet = pindex; return pindexBest->nHeight - pindex->nHeight + 1; } int CMerkleTx::GetBlocksToMaturity() const { if (!(IsCoinBase() || IsCoinStake())) return 0; int depth = GetDepthInMainChain(); if (depth == 0) // Not in the blockchain return COINBASE_MATURITY; return max(0, COINBASE_MATURITY - (depth - 1)); } bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs) { if (fClient) { if (!IsInMainChain() && !ClientConnectInputs()) return false; return CTransaction::AcceptToMemoryPool(txdb, false); } else { return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs); } } bool CMerkleTx::AcceptToMemoryPool() { CTxDB txdb("r"); return AcceptToMemoryPool(txdb); } bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs) { { LOCK(mempool.cs); // Add previous supporting transactions first BOOST_FOREACH(CMerkleTx& tx, vtxPrev) { if (!(tx.IsCoinBase() || tx.IsCoinStake())) { uint256 hash = tx.GetHash(); if (!mempool.exists(hash) && !txdb.ContainsTx(hash)) tx.AcceptToMemoryPool(txdb, fCheckInputs); } } return AcceptToMemoryPool(txdb, fCheckInputs); } return false; } bool CWalletTx::AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); } int CTxIndex::GetDepthInMainChain() const { // Read block header CBlock block; if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false)) return 0; // Find the block in the index map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash()); if (mi == mapBlockIndex.end()) return 0; CBlockIndex* pindex = (*mi).second; if (!pindex || !pindex->IsInMainChain()) return 0; return 1 + nBestHeight - pindex->nHeight; } // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock) { { LOCK(cs_main); { LOCK(mempool.cs); if (mempool.exists(hash)) { tx = mempool.lookup(hash); return true; } } CTxDB txdb("r"); CTxIndex txindex; if (tx.ReadFromDisk(txdb, hash, txindex)) { CBlock block; if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false)) hashBlock = block.GetHash(); return true; } // look for transaction in disconnected blocks to find orphaned CoinBase and CoinStake transactions BOOST_FOREACH(PAIRTYPE(const uint256, CBlockIndex*)& item, mapBlockIndex) { CBlockIndex* pindex = item.second; if (pindex == pindexBest || pindex->pnext != 0) continue; CBlock block; if (!block.ReadFromDisk(pindex)) continue; BOOST_FOREACH(const CTransaction& txOrphan, block.vtx) { if (txOrphan.GetHash() == hash) { tx = txOrphan; return true; } } } } return false; } ////////////////////////////////////////////////////////////////////////////// // // CBlock and CBlockIndex // bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions) { if (!fReadTransactions) { *this = pindex->GetBlockHeader(); return true; } if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions)) return false; if (GetHash() != pindex->GetBlockHash()) return error("CBlock::ReadFromDisk() : GetHash() doesn't match index"); return true; } uint256 static GetOrphanRoot(const CBlock* pblock) { // Work back to the first block in the orphan chain while (mapOrphanBlocks.count(pblock->hashPrevBlock)) pblock = mapOrphanBlocks[pblock->hashPrevBlock]; return pblock->GetHash(); } // ppcoin: find block wanted by given orphan block uint256 WantedByOrphan(const CBlock* pblockOrphan) { // Work back to the first block in the orphan chain while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock)) pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock]; return pblockOrphan->hashPrevBlock; } // // minimum amount of work that could possibly be required nTime after // minimum work required was nBase // unsigned int ComputeMinWork(unsigned int nBase, int64 nTime) { CBigNum bnResult; bnResult.SetCompact(nBase); bnResult *= 2; while (nTime > 0 && bnResult < POW_MAX_TARGET) { // Maximum 200% adjustment per day... bnResult *= 2; nTime -= 24 * 60 * 60; } if (bnResult > POW_MAX_TARGET) bnResult = POW_MAX_TARGET; return bnResult.GetCompact(); } // ppcoin: find last block index up to pindex const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake) { while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake)) pindex = pindex->pprev; return pindex; } bool CheckProofOfWork(uint256 hash, unsigned int nBits, bool triggerErrors) { CBigNum bnTarget; bnTarget.SetCompact(nBits); // Check range if (bnTarget <= 0 || bnTarget > POW_MAX_TARGET) return triggerErrors ? error("CheckProofOfWork() : nBits below minimum work") : false; // Check proof of work matches claimed amount if (hash > bnTarget.getuint256()) return triggerErrors ? error("CheckProofOfWork() : hash doesn't match nBits") : false; return true; } // Return maximum amount of blocks that other nodes claim to have int GetNumBlocksOfPeers() { return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate()); } bool IsInitialBlockDownload() { if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate()) return true; static int64 nLastUpdate; static CBlockIndex* pindexLastBest; if (pindexBest != pindexLastBest) { pindexLastBest = pindexBest; nLastUpdate = GetTime(); } return (GetTime() - nLastUpdate < 10 && pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60); } void static InvalidChainFound(CBlockIndex* pindexNew) { if (pindexNew->bnChainTrust > bnBestInvalidTrust) { bnBestInvalidTrust = pindexNew->bnChainTrust; CTxDB().WriteBestInvalidTrust(bnBestInvalidTrust); MainFrameRepaint(); } printf("InvalidChainFound: invalid block=%s height=%d trust=%s\n", pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight, CBigNum(pindexNew->bnChainTrust).ToString().c_str()); printf("InvalidChainFound: current best=%s height=%d trust=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, CBigNum(bnBestChainTrust).ToString().c_str()); // ppcoin: should not enter safe mode for longer invalid chain } void CBlock::UpdateTime(const CBlockIndex* pindexPrev) { nTime = max(GetBlockTime(), GetAdjustedTime()); } bool CTransaction::DisconnectInputs(CTxDB& txdb) { // Relinquish previous transactions' spent pointers if (!IsCoinBase()) { BOOST_FOREACH(const CTxIn& txin, vin) { COutPoint prevout = txin.prevout; // Get prev txindex from disk CTxIndex txindex; if (!txdb.ReadTxIndex(prevout.hash, txindex)) return error("DisconnectInputs() : ReadTxIndex failed"); if (prevout.n >= txindex.vSpent.size()) return error("DisconnectInputs() : prevout.n out of range"); // Mark outpoint as not spent txindex.vSpent[prevout.n].SetNull(); // Write back if (!txdb.UpdateTxIndex(prevout.hash, txindex)) return error("DisconnectInputs() : UpdateTxIndex failed"); } } // Remove transaction from index // This can fail if a duplicate of this transaction was in a chain that got // reorganized away. This is only possible if this transaction was completely // spent, so erasing it would be a no-op anway. txdb.EraseTxIndex(*this); return true; } bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool, bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid) { // FetchInputs can return false either because we just haven't seen some inputs // (in which case the transaction should be stored as an orphan) // or because the transaction is malformed (in which case the transaction should // be dropped). If tx is definitely invalid, fInvalid will be set to true. fInvalid = false; if (IsCoinBase()) return true; // Coinbase transactions have no inputs to fetch. for (unsigned int i = 0; i < vin.size(); i++) { COutPoint prevout = vin[i].prevout; if (inputsRet.count(prevout.hash)) continue; // Got it already // Read txindex CTxIndex& txindex = inputsRet[prevout.hash].first; bool fFound = true; if ((fBlock || fMiner) && mapTestPool.count(prevout.hash)) { // Get txindex from current proposed changes txindex = mapTestPool.find(prevout.hash)->second; } else { // Read txindex from txdb fFound = txdb.ReadTxIndex(prevout.hash, txindex); } if (!fFound && (fBlock || fMiner)) return fMiner ? false : error("FetchInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str()); // Read txPrev CTransaction& txPrev = inputsRet[prevout.hash].second; if (!fFound || txindex.pos == CDiskTxPos(1,1,1)) { // Get prev tx from single transactions in memory { LOCK(mempool.cs); if (!mempool.exists(prevout.hash)) return error("FetchInputs() : %s mempool Tx prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str()); txPrev = mempool.lookup(prevout.hash); } if (!fFound) txindex.vSpent.resize(txPrev.vout.size()); } else { // Get prev tx from disk if (!txPrev.ReadFromDisk(txindex.pos)) return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str()); } } // Make sure all prevout.n's are valid: for (unsigned int i = 0; i < vin.size(); i++) { const COutPoint prevout = vin[i].prevout; assert(inputsRet.count(prevout.hash) != 0); const CTxIndex& txindex = inputsRet[prevout.hash].first; const CTransaction& txPrev = inputsRet[prevout.hash].second; if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size()) { // Revisit this if/when transaction replacement is implemented and allows // adding inputs: fInvalid = true; return DoS(100, error("FetchInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str())); } } return true; } const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const { MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash); if (mi == inputs.end()) throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found"); const CTransaction& txPrev = (mi->second).second; if (input.prevout.n >= txPrev.vout.size()) throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range"); return txPrev.vout[input.prevout.n]; } int64 CTransaction::GetValueIn(const MapPrevTx& inputs) const { if (IsCoinBase()) return 0; int64 nResult = 0; for (unsigned int i = 0; i < vin.size(); i++) { nResult += GetOutputFor(vin[i], inputs).nValue; } return nResult; } unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const { if (IsCoinBase()) return 0; unsigned int nSigOps = 0; for (unsigned int i = 0; i < vin.size(); i++) { const CTxOut& prevout = GetOutputFor(vin[i], inputs); if (prevout.scriptPubKey.IsPayToScriptHash()) nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig); } return nSigOps; } bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs, map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx, const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash) { // Take over previous transactions' spent pointers // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain // fMiner is true when called from the internal bitcoin miner // ... both are false when called from CTransaction::AcceptToMemoryPool if (!IsCoinBase()) { int64 nValueIn = 0; int64 nFees = 0; for (unsigned int i = 0; i < vin.size(); i++) { COutPoint prevout = vin[i].prevout; assert(inputs.count(prevout.hash) > 0); CTxIndex& txindex = inputs[prevout.hash].first; CTransaction& txPrev = inputs[prevout.hash].second; if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size()) return DoS(100, error("ConnectInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str())); // If prev is coinbase/coinstake, check that it's matured if (txPrev.IsCoinBase() || txPrev.IsCoinStake()) for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev) if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile) return error("ConnectInputs() : tried to spend coinbase/coinstake at depth %d", pindexBlock->nHeight - pindex->nHeight); // ppcoin: check transaction timestamp if (txPrev.nTime > nTime) return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction")); // Check for negative or overflow input values nValueIn += txPrev.vout[prevout.n].nValue; if (!IsValidAmount(txPrev.vout[prevout.n].nValue) || !IsValidAmount(nValueIn)) return DoS(100, error("ConnectInputs() : txin values out of range")); } // The first loop above does all the inexpensive checks. // Only if ALL inputs pass do we perform expensive ECDSA signature checks. // Helps prevent CPU exhaustion attacks. for (unsigned int i = 0; i < vin.size(); i++) { COutPoint prevout = vin[i].prevout; assert(inputs.count(prevout.hash) > 0); CTxIndex& txindex = inputs[prevout.hash].first; CTransaction& txPrev = inputs[prevout.hash].second; // Check for conflicts (double-spend) // This doesn't trigger the DoS code on purpose; if it did, it would make it easier // for an attacker to attempt to split the network. if (!txindex.vSpent[prevout.n].IsNull()) return fMiner ? false : error("ConnectInputs() : %s prev tx already used at %s", GetHash().ToString().substr(0,10).c_str(), txindex.vSpent[prevout.n].ToString().c_str()); // Skip ECDSA signature verification when connecting blocks (fBlock=true) // before the last blockchain checkpoint. This is safe because block merkle hashes are // still computed and checked, and any change will be caught at the next checkpoint. if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate()))) { // Verify signature if (!VerifySignature(txPrev, *this, i, fStrictPayToScriptHash, 0)) { // only during transition phase for P2SH: do not invoke anti-DoS code for // potentially old clients relaying bad P2SH transactions if (fStrictPayToScriptHash && VerifySignature(txPrev, *this, i, false, 0)) return error("ConnectInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str()); return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str())); } } // Mark outpoints as spent txindex.vSpent[prevout.n] = posThisTx; // Write back if (fBlock || fMiner) { mapTestPool[prevout.hash] = txindex; } } if (IsCoinStake()) { // ppcoin: coin stake tx earns reward instead of paying fee uint64 nCoinAge; if (!GetCoinAge(txdb, nCoinAge)) return error("ConnectInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str()); int64 nStakeReward = GetValueOut() - nValueIn; if (nStakeReward > GetProofOfStakeReward(nCoinAge, pindexBlock->pprev->nHeight) - GetMinFee() + MIN_TX_FEES) return DoS(100, error("ConnectInputs() : %s stake reward exceeded", GetHash().ToString().substr(0,10).c_str())); } else { if (nValueIn < GetValueOut()) return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str())); // Tally transaction fees int64 nTxFee = nValueIn - GetValueOut(); if (nTxFee < 0) return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str())); // ppcoin: enforce transaction fees for every block if (nTxFee < GetMinFee()) return fBlock? DoS(100, error("ConnectInputs() : %s not paying required fee=%s, paid=%s", GetHash().ToString().substr(0,10).c_str(), FormatMoney(GetMinFee()).c_str(), FormatMoney(nTxFee).c_str())) : false; nFees += nTxFee; if (!IsValidAmount(nFees)) return DoS(100, error("ConnectInputs() : nFees out of range")); } } return true; } bool CTransaction::ClientConnectInputs() { if (IsCoinBase()) return false; // Take over previous transactions' spent pointers { LOCK(mempool.cs); int64 nValueIn = 0; for (unsigned int i = 0; i < vin.size(); i++) { // Get prev tx from single transactions in memory COutPoint prevout = vin[i].prevout; if (!mempool.exists(prevout.hash)) return false; CTransaction& txPrev = mempool.lookup(prevout.hash); if (prevout.n >= txPrev.vout.size()) return false; // Verify signature if (!VerifySignature(txPrev, *this, i, true, 0)) return error("ConnectInputs() : VerifySignature failed"); ///// this is redundant with the mempool.mapNextTx stuff, ///// not sure which I want to get rid of ///// this has to go away now that posNext is gone // // Check for conflicts // if (!txPrev.vout[prevout.n].posNext.IsNull()) // return error("ConnectInputs() : prev tx already used"); // // // Flag outpoints as used // txPrev.vout[prevout.n].posNext = posThisTx; nValueIn += txPrev.vout[prevout.n].nValue; if (!IsValidAmount(txPrev.vout[prevout.n].nValue) || !IsValidAmount(nValueIn)) { return error("ClientConnectInputs() : txin values out of range"); } } if (GetValueOut() > nValueIn) { return false; } } return true; } bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex) { // Disconnect in reverse order for (int i = vtx.size()-1; i >= 0; i--) if (!vtx[i].DisconnectInputs(txdb)) return false; // Update block index on disk without changing it in memory. // The memory index structure will be changed after the db commits. if (pindex->pprev) { CDiskBlockIndex blockindexPrev(pindex->pprev); blockindexPrev.hashNext = 0; if (!txdb.WriteBlockIndex(blockindexPrev)) return error("DisconnectBlock() : WriteBlockIndex failed"); } // ppcoin: clean up wallet after disconnecting coinstake BOOST_FOREACH(CTransaction& tx, vtx) SyncWithWallets(tx, this, false, false); return true; } bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex) { // Check it again in case a previous version let a bad block in if (!CheckBlock()) return false; // Check coinbase reward if (IsProofOfWork() && vtx[0].GetValueOut() > (IsProofOfWork() ? (GetProofOfWorkReward(pindex->pprev ? pindex->pprev->nHeight : -1) - vtx[0].GetMinFee() + MIN_TX_FEES) : 0)) return DoS(50, error("CheckBlock() : coinbase reward exceeded %s > %s", FormatMoney(vtx[0].GetValueOut()).c_str(), FormatMoney(IsProofOfWork() ? GetProofOfWorkReward(pindex->pprev ? pindex->pprev->nHeight : -1) : 0).c_str())); // Do not allow blocks that contain transactions which 'overwrite' older transactions, // unless those are already completely spent. // If such overwrites are allowed, coinbases and transactions depending upon those // can be duplicated to remove the ability to spend the first instance -- even after // being sent to another address. // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information. // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool // already refuses previously-known transaction id's entirely. BOOST_FOREACH(CTransaction& tx, vtx) { CTxIndex txindexOld; if (txdb.ReadTxIndex(tx.GetHash(), txindexOld)) { BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent) if (pos.IsNull()) return false; } } // BIP16 didn't become active until Apr 1 2012 int64 nBIP16SwitchTime = 1333238400; bool fStrictPayToScriptHash = (pindex->nTime >= nBIP16SwitchTime); //// issue here: it doesn't know the version unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size()); map<uint256, CTxIndex> mapQueuedChanges; int64 nFees = 0; int64 nValueIn = 0; int64 nValueOut = 0; unsigned int nSigOps = 0; BOOST_FOREACH(CTransaction& tx, vtx) { nSigOps += tx.GetLegacySigOpCount(); if (nSigOps > MAX_BLOCK_SIGOPS) return DoS(100, error("ConnectBlock() : too many sigops")); CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos); nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION); MapPrevTx mapInputs; if (tx.IsCoinBase()) nValueOut += tx.GetValueOut(); else { bool fInvalid; if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid)) return false; if (fStrictPayToScriptHash) { // Add in sigops done by pay-to-script-hash inputs; // this is to prevent a "rogue miner" from creating // an incredibly-expensive-to-validate block. nSigOps += tx.GetP2SHSigOpCount(mapInputs); if (nSigOps > MAX_BLOCK_SIGOPS) return DoS(100, error("ConnectBlock() : too many sigops")); } int64 nTxValueIn = tx.GetValueIn(mapInputs); int64 nTxValueOut = tx.GetValueOut(); nValueIn += nTxValueIn; nValueOut += nTxValueOut; if (!tx.IsCoinStake()) nFees += nTxValueIn - nTxValueOut; if (!tx.ConnectInputs(txdb, mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fStrictPayToScriptHash)) return false; } mapQueuedChanges[tx.GetHash()] = CTxIndex(posThisTx, tx.vout.size()); } // ppcoin: track money supply and mint amount info pindex->nMint = nValueOut - nValueIn + nFees; pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn; if (!txdb.WriteBlockIndex(CDiskBlockIndex(pindex))) return error("Connect() : WriteBlockIndex for pindex failed"); // Write queued txindex changes for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi) { if (!txdb.UpdateTxIndex((*mi).first, (*mi).second)) return error("ConnectBlock() : UpdateTxIndex failed"); } // ppcoin: fees are not collected by miners as in bitcoin // ppcoin: fees are destroyed to compensate the entire network if (fDebug && GetBoolArg("-printcreation")) printf("ConnectBlock() : destroy=%s nFees=%"PRI64d"\n", FormatMoney(nFees).c_str(), nFees); // Update block index on disk without changing it in memory. // The memory index structure will be changed after the db commits. if (pindex->pprev) { CDiskBlockIndex blockindexPrev(pindex->pprev); blockindexPrev.hashNext = pindex->GetBlockHash(); if (!txdb.WriteBlockIndex(blockindexPrev)) return error("ConnectBlock() : WriteBlockIndex for blockindexPrev failed"); } // Watch for transactions paying to me BOOST_FOREACH(CTransaction& tx, vtx) SyncWithWallets(tx, this, true); return true; } bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew) { printf("REORGANIZE\n"); // Find the fork CBlockIndex* pfork = pindexBest; CBlockIndex* plonger = pindexNew; while (pfork != plonger) { while (plonger->nHeight > pfork->nHeight) if (!(plonger = plonger->pprev)) return error("Reorganize() : plonger->pprev is null"); if (pfork == plonger) break; if (!(pfork = pfork->pprev)) return error("Reorganize() : pfork->pprev is null"); } // List of what to disconnect vector<CBlockIndex*> vDisconnect; for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev) vDisconnect.push_back(pindex); // List of what to connect vector<CBlockIndex*> vConnect; for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev) vConnect.push_back(pindex); reverse(vConnect.begin(), vConnect.end()); printf("REORGANIZE: Disconnect %i blocks; %s..%s\n", vDisconnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexBest->GetBlockHash().ToString().substr(0,20).c_str()); printf("REORGANIZE: Connect %i blocks; %s..%s\n", vConnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->GetBlockHash().ToString().substr(0,20).c_str()); // Disconnect shorter branch vector<CTransaction> vResurrect; BOOST_FOREACH(CBlockIndex* pindex, vDisconnect) { CBlock block; if (!block.ReadFromDisk(pindex)) return error("Reorganize() : ReadFromDisk for disconnect failed"); if (!block.DisconnectBlock(txdb, pindex)) return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str()); // Queue memory transactions to resurrect BOOST_FOREACH(const CTransaction& tx, block.vtx) if (!(tx.IsCoinBase() || tx.IsCoinStake())) vResurrect.push_back(tx); } // Connect longer branch vector<CTransaction> vDelete; for (unsigned int i = 0; i < vConnect.size(); i++) { CBlockIndex* pindex = vConnect[i]; CBlock block; if (!block.ReadFromDisk(pindex)) return error("Reorganize() : ReadFromDisk for connect failed"); if (!block.ConnectBlock(txdb, pindex)) { // Invalid block txdb.TxnAbort(); return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str()); } // Queue memory transactions to delete BOOST_FOREACH(const CTransaction& tx, block.vtx) vDelete.push_back(tx); } if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash())) return error("Reorganize() : WriteHashBestChain failed"); // Make sure it's successfully written to disk before changing memory structure if (!txdb.TxnCommit()) return error("Reorganize() : TxnCommit failed"); // Disconnect shorter branch BOOST_FOREACH(CBlockIndex* pindex, vDisconnect) if (pindex->pprev) pindex->pprev->pnext = NULL; // Connect longer branch BOOST_FOREACH(CBlockIndex* pindex, vConnect) if (pindex->pprev) pindex->pprev->pnext = pindex; // Resurrect memory transactions that were in the disconnected branch BOOST_FOREACH(CTransaction& tx, vResurrect) tx.AcceptToMemoryPool(txdb, false); // Delete redundant memory transactions that are in the connected branch BOOST_FOREACH(CTransaction& tx, vDelete) mempool.remove(tx); printf("REORGANIZE: done\n"); return true; } // Called from inside SetBestChain: attaches a block to the new best chain being built bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew) { uint256 hash = GetHash(); // Adding to current best branch if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash)) { txdb.TxnAbort(); InvalidChainFound(pindexNew); return false; } if (!txdb.TxnCommit()) return error("SetBestChain() : TxnCommit failed"); // Add to current best branch pindexNew->pprev->pnext = pindexNew; // Delete redundant memory transactions BOOST_FOREACH(CTransaction& tx, vtx) mempool.remove(tx); return true; } bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew) { uint256 hash = GetHash(); if (!txdb.TxnBegin()) return error("SetBestChain() : TxnBegin failed"); if (pindexGenesisBlock == NULL && hash == GENESIS_HASH) { txdb.WriteHashBestChain(hash); if (!txdb.TxnCommit()) return error("SetBestChain() : TxnCommit failed"); pindexGenesisBlock = pindexNew; } else if (hashPrevBlock == hashBestChain) { if (!SetBestChainInner(txdb, pindexNew)) return error("SetBestChain() : SetBestChainInner failed"); } else { // the first block in the new chain that will cause it to become the new best chain CBlockIndex *pindexIntermediate = pindexNew; // list of blocks that need to be connected afterwards std::vector<CBlockIndex*> vpindexSecondary; // Reorganize is costly in terms of db load, as it works in a single db transaction. // Try to limit how much needs to be done inside while (pindexIntermediate->pprev && pindexIntermediate->pprev->bnChainTrust > pindexBest->bnChainTrust) { vpindexSecondary.push_back(pindexIntermediate); pindexIntermediate = pindexIntermediate->pprev; } if (!vpindexSecondary.empty()) printf("Postponing %i reconnects\n", vpindexSecondary.size()); // Switch to new best branch if (!Reorganize(txdb, pindexIntermediate)) { txdb.TxnAbort(); InvalidChainFound(pindexNew); return error("SetBestChain() : Reorganize failed"); } // Connect futher blocks BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vpindexSecondary) { CBlock block; if (!block.ReadFromDisk(pindex)) { printf("SetBestChain() : ReadFromDisk failed\n"); break; } if (!txdb.TxnBegin()) { printf("SetBestChain() : TxnBegin 2 failed\n"); break; } // errors now are not fatal, we still did a reorganisation to a new chain in a valid way if (!block.SetBestChainInner(txdb, pindex)) break; } } // Update best block in wallet (so we can detect restored wallets) bool fIsInitialDownload = IsInitialBlockDownload(); if (!fIsInitialDownload) { const CBlockLocator locator(pindexNew); ::SetBestChain(locator); } // New best block hashBestChain = hash; pindexBest = pindexNew; nBestHeight = pindexBest->nHeight; bnBestChainTrust = pindexNew->bnChainTrust; nTimeBestReceived = GetTime(); nTransactionsUpdated++; printf("SetBestChain: new best=%s height=%d trust=%s moneysupply=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainTrust.ToString().c_str(), FormatMoney(pindexBest->nMoneySupply).c_str()); std::string strCmd = GetArg("-blocknotify", ""); if (!fIsInitialDownload && !strCmd.empty()) { boost::replace_all(strCmd, "%s", hashBestChain.GetHex()); boost::thread t(runCommand, strCmd); // thread runs free } return true; } // ppcoin: total coin age spent in transaction, in the unit of coin-days. // Only those coins meeting minimum age requirement counts. As those // transactions not in main chain are not currently indexed so we // might not find out about their coin age. Older transactions are // guaranteed to be in main chain by sync-checkpoint. This rule is // introduced to help nodes establish a consistent view of the coin // age (trust score) of competing branches. bool CTransaction::GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const { CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds nCoinAge = 0; if (IsCoinBase()) return true; BOOST_FOREACH(const CTxIn& txin, vin) { // First try finding the previous transaction in database CTransaction txPrev; CTxIndex txindex; if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex)) continue; // previous transaction not in main chain if (nTime < txPrev.nTime) return false; // Transaction timestamp violation // Read block header CBlock block; if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false)) return false; // unable to read block of previous transaction if (block.GetBlockTime() + STAKE_MIN_AGE > nTime) continue; // only count coins meeting min age requirement int64 nValueIn = txPrev.vout[txin.prevout.n].nValue; bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT; if (fDebug && GetBoolArg("-printcoinage")) { printf("coin age nValueIn=%-12"PRI64d" nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str()); } } CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60); if (fDebug && GetBoolArg("-printcoinage")) printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str()); nCoinAge = bnCoinDay.getuint64(); return true; } // ppcoin: total coin age spent in block, in the unit of coin-days. bool CBlock::GetCoinAge(uint64& nCoinAge) const { nCoinAge = 0; CTxDB txdb("r"); BOOST_FOREACH(const CTransaction& tx, vtx) { uint64 nTxCoinAge; if (tx.GetCoinAge(txdb, nTxCoinAge)) nCoinAge += nTxCoinAge; else return false; } if (nCoinAge == 0) // block coin age minimum 1 coin-day nCoinAge = 1; if (fDebug && GetBoolArg("-printcoinage")) printf("block coin age total nCoinDays=%"PRI64d"\n", nCoinAge); return true; } bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos) { // Check for duplicate uint256 hash = GetHash(); if (mapBlockIndex.count(hash)) return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str()); // Construct new block index object CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this); if (!pindexNew) return error("AddToBlockIndex() : new CBlockIndex failed"); pindexNew->phashBlock = &hash; map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock); if (miPrev != mapBlockIndex.end()) { pindexNew->pprev = (*miPrev).second; pindexNew->nHeight = pindexNew->pprev->nHeight + 1; } // ppcoin: compute chain trust score pindexNew->bnChainTrust = (pindexNew->pprev ? pindexNew->pprev->bnChainTrust : 0) + pindexNew->GetBlockTrust(); // ppcoin: compute stake entropy bit for stake modifier if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit())) return error("AddToBlockIndex() : SetStakeEntropyBit() failed"); // ppcoin: record proof-of-stake hash value if (pindexNew->IsProofOfStake()) { if (!mapProofOfStake.count(hash)) return error("AddToBlockIndex() : hashProofOfStake not found in map"); pindexNew->hashProofOfStake = mapProofOfStake[hash]; } // ppcoin: compute stake modifier uint64 nStakeModifier = 0; bool fGeneratedStakeModifier = false; if (!ComputeNextStakeModifier(pindexNew, nStakeModifier, fGeneratedStakeModifier)) return error("AddToBlockIndex() : ComputeNextStakeModifier() failed"); pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier); pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew); if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum)) return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016"PRI64x", checksum=0x%08x", pindexNew->nHeight, nStakeModifier, pindexNew->nStakeModifierChecksum); // Add to mapBlockIndex map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first; if (pindexNew->IsProofOfStake()) setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime)); pindexNew->phashBlock = &((*mi).first); // Write to disk block index CTxDB txdb; if (!txdb.TxnBegin()) return false; txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew)); if (!txdb.TxnCommit()) return false; // New best if (pindexNew->bnChainTrust > bnBestChainTrust) if (!SetBestChain(txdb, pindexNew)) return false; txdb.Close(); if (pindexNew == pindexBest) { // Notify UI to display prev block's coinbase if it was ours static uint256 hashPrevBestCoinBase; UpdatedTransaction(hashPrevBestCoinBase); hashPrevBestCoinBase = vtx[0].GetHash(); } MainFrameRepaint(); return true; } bool CBlock::CheckBlock() const { // These are checks that are independent of context // that can be verified before saving an orphan block. // Size limits if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE) return DoS(100, error("CheckBlock() : size limits failed")); // Check proof of work matches claimed amount if (IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits)) return DoS(50, error("CheckBlock() : proof of work failed")); // Check timestamp if (GetBlockTime() > GetAdjustedTime() + MAX_CLOCK_DRIFT) return error("CheckBlock() : block timestamp too far in the future"); // First transaction must be coinbase, the rest must not be if (vtx.empty() || !vtx[0].IsCoinBase()) return DoS(100, error("CheckBlock() : first tx is not coinbase")); for (unsigned int i = 1; i < vtx.size(); i++) if (vtx[i].IsCoinBase()) return DoS(100, error("CheckBlock() : more than one coinbase")); // ppcoin: only the second transaction can be the optional coinstake for (size_t i = 2; i < vtx.size(); i++) if (vtx[i].IsCoinStake()) return DoS(100, error("CheckBlock() : coinstake in wrong position")); // ppcoin: coinbase output should be empty if proof-of-stake block if (IsProofOfStake() && (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty())) return error("CheckBlock() : coinbase output not empty for proof-of-stake block"); // Check coinbase timestamp if (GetBlockTime() > (int64)vtx[0].nTime + MAX_CLOCK_DRIFT) return DoS(50, error("CheckBlock() : coinbase timestamp is too early (block: %d, vtx[0]: %d)", GetBlockTime(), vtx[0].nTime)); // Check coinstake timestamp if (IsProofOfStake() && !CheckCoinStakeTimestamp(GetBlockTime(), (int64)vtx[1].nTime)) return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%u nTimeTx=%u", GetBlockTime(), vtx[1].nTime)); // Check coinbase reward // // Note: We're not doing the reward check here, because we need to know the block height. // Check inside ConnectBlock instead. // Check transactions BOOST_FOREACH(const CTransaction& tx, vtx) { if (!tx.CheckTransaction()) return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed")); // ppcoin: check transaction timestamp if (GetBlockTime() < (int64)tx.nTime) return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp")); } // Check for duplicate txids. This is caught by ConnectInputs(), // but catching it earlier avoids a potential DoS attack: set<uint256> uniqueTx; BOOST_FOREACH(const CTransaction& tx, vtx) { uniqueTx.insert(tx.GetHash()); } if (uniqueTx.size() != vtx.size()) return DoS(100, error("CheckBlock() : duplicate transaction")); unsigned int nSigOps = 0; BOOST_FOREACH(const CTransaction& tx, vtx) { nSigOps += tx.GetLegacySigOpCount(); } if (nSigOps > MAX_BLOCK_SIGOPS) return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount")); // Check merkleroot if (hashMerkleRoot != BuildMerkleTree()) return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch")); // ppcoin: check block signature if (!CheckBlockSignature()) return DoS(100, error("CheckBlock() : bad block signature")); return true; } bool CBlock::AcceptBlock() { // Check for duplicate uint256 hash = GetHash(); if (mapBlockIndex.count(hash)) return error("AcceptBlock() : block already in mapBlockIndex"); // Get prev block index map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock); if (mi == mapBlockIndex.end()) return DoS(10, error("AcceptBlock() : prev block not found")); CBlockIndex* pindexPrev = (*mi).second; int nHeight = pindexPrev->nHeight+1; // Check proof-of-work or proof-of-stake if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake())) return DoS(100, error("AcceptBlock() : incorrect proof-of-work/proof-of-stake")); // Check timestamp against prev if (GetBlockTime() <= pindexPrev->GetMedianTimePast() || GetBlockTime() + MAX_CLOCK_DRIFT < pindexPrev->GetBlockTime()) return error("AcceptBlock() : block's timestamp is too early"); // Check that all transactions are finalized BOOST_FOREACH(const CTransaction& tx, vtx) if (!tx.IsFinal(nHeight, GetBlockTime())) return DoS(10, error("AcceptBlock() : contains a non-final transaction")); // Check that the block chain matches the known block chain up to a hardened checkpoint if (!Checkpoints::CheckHardened(nHeight, hash)) return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lockin at %d", nHeight)); // ppcoin: check that the block satisfies synchronized checkpoint if (!Checkpoints::CheckSync(hash, pindexPrev)) return error("AcceptBlock() : rejected by synchronized checkpoint"); // Write block to history file if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION))) return error("AcceptBlock() : out of disk space"); unsigned int nFile = -1; unsigned int nBlockPos = 0; if (!WriteToDisk(nFile, nBlockPos)) return error("AcceptBlock() : WriteToDisk failed"); if (!AddToBlockIndex(nFile, nBlockPos)) return error("AcceptBlock() : AddToBlockIndex failed"); // Relay inventory, but don't relay old inventory during initial block download int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate(); if (hashBestChain == hash) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate)) pnode->PushInventory(CInv(MSG_BLOCK, hash)); } // ppcoin: check pending sync-checkpoint Checkpoints::AcceptPendingSyncCheckpoint(); return true; } bool ProcessBlock(CNode* pfrom, CBlock* pblock) { // Check for duplicate uint256 hash = pblock->GetHash(); if (mapBlockIndex.count(hash)) return error("ProcessBlock() : already have block %d %s", mapBlockIndex.at(hash)->nHeight, hash.ToString().substr(0,20).c_str()); if (mapOrphanBlocks.count(hash)) return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str()); // ppcoin: check proof-of-stake if (pblock->IsProofOfStake()) { std::pair<COutPoint, unsigned int> proofOfStake = pblock->GetProofOfStake(); if (pindexBest->IsProofOfStake() && proofOfStake.first == pindexBest->prevoutStake) { if (!pblock->CheckBlockSignature()) { if (pfrom) pfrom->Misbehaving(100); return error("ProcessBlock() : invalid signature in a duplicate Proof-of-Stake kernel"); } RelayBlock(*pblock, hash); BlacklistProofOfStake(proofOfStake, hash); CTxDB txdb; CBlock bestPrevBlock; bestPrevBlock.ReadFromDisk(pindexBest->pprev); if (!bestPrevBlock.SetBestChain(txdb, pindexBest->pprev)) return error("ProcessBlock() : Proof-of-stake rollback failed"); return error("ProcessBlock() : duplicate Proof-of-Stake kernel (%s, %d) in block %s", pblock->GetProofOfStake().first.ToString().c_str(), pblock->GetProofOfStake().second, hash.ToString().c_str()); } else if (setStakeSeen.count(proofOfStake) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash)) { return error("ProcessBlock() : duplicate Proof-of-Stake kernel (%s, %d) in block %s", proofOfStake.first.ToString().c_str(), proofOfStake.second, hash.ToString().c_str()); } } // Preliminary checks if (!pblock->CheckBlock()) return error("ProcessBlock() : CheckBlock FAILED"); CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint(); if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash)) { // Extra checks to prevent "fill up memory by spamming with bogus blocks" int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime; CBigNum bnNewBlock; bnNewBlock.SetCompact(pblock->nBits); CBigNum bnRequired; bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, pblock->IsProofOfStake())->nBits, deltaTime)); if (bnNewBlock > bnRequired) { if (pfrom) pfrom->Misbehaving(100); return error("ProcessBlock() : block with too little %s", pblock->IsProofOfStake()? "proof-of-stake" : "proof-of-work"); } } // ppcoin: ask for pending sync-checkpoint if any if (!IsInitialBlockDownload()) Checkpoints::AskForPendingSyncCheckpoint(pfrom); // We remove the previous block from the blacklisted kernels, if needed CleanProofOfStakeBlacklist(pblock->hashPrevBlock); // Find the previous block std::map<uint256, CBlockIndex*>::iterator parentBlockIt = mapBlockIndex.find(pblock->hashPrevBlock); // If we don't already have it, shunt off the block to the holding area until we get its parent if (parentBlockIt == mapBlockIndex.end()) { printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str()); CBlock* pblock2 = new CBlock(*pblock); // ppcoin: check proof-of-stake if (pblock2->IsProofOfStake()) setStakeSeenOrphan.insert(pblock2->GetProofOfStake()); mapOrphanBlocks.insert(make_pair(hash, pblock2)); mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2)); // Ask this guy to fill in what we're missing if (pfrom) { pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2)); // ppcoin: getblocks may not obtain the ancestor block rejected // earlier by duplicate-stake check so we ask for it again directly if (!IsInitialBlockDownload()) { pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2))); } } return true; } // ppcoin: verify hash target and signature of coinstake tx if (pblock->IsProofOfStake()) { uint256 hashProofOfStake = 0; const CBlockIndex * pindexPrev = parentBlockIt->second; if (!CheckProofOfStake(pindexPrev, pblock->vtx[1], pblock->nBits, hashProofOfStake)) { printf("WARNING: ProcessBlock(): check proof-of-stake failed for block %s\n", hash.ToString().c_str()); return false; // do not error here as we expect this during initial block download } if (!mapProofOfStake.count(hash)) // add to mapProofOfStake { mapProofOfStake.insert(make_pair(hash, hashProofOfStake)); } } // Store to disk if (!pblock->AcceptBlock()) return error("ProcessBlock() : AcceptBlock FAILED"); // Recursively process any orphan blocks that depended on this one vector<uint256> vWorkQueue; vWorkQueue.push_back(hash); for (unsigned int i = 0; i < vWorkQueue.size(); i++) { uint256 hashPrev = vWorkQueue[i]; CBlockIndex* pindexPrev = mapBlockIndex.at(hashPrev); for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev); mi != mapOrphanBlocksByPrev.upper_bound(hashPrev); ++mi) { bool validated = true; CBlock* pblockOrphan = (*mi).second; uint256 orphanHash = pblockOrphan->GetHash(); if (pblockOrphan->IsProofOfStake()) { uint256 hashProofOfStake = 0; if (CheckProofOfStake(pindexPrev, pblockOrphan->vtx[1], pblockOrphan->nBits, hashProofOfStake)) { if (!mapProofOfStake.count(orphanHash)) mapProofOfStake.insert(make_pair(orphanHash, hashProofOfStake)); validated = true; } else { validated = false; } } if (validated && pblockOrphan->AcceptBlock()) vWorkQueue.push_back(orphanHash); mapOrphanBlocks.erase(orphanHash); setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake()); delete pblockOrphan; } mapOrphanBlocksByPrev.erase(hashPrev); } printf("ProcessBlock: ACCEPTED\n"); // ppcoin: if responsible for sync-checkpoint send it if (pfrom && !CHECKPOINT_PRIVATE_KEY.empty()) Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint()); return true; } // ppcoin: sign block bool CBlock::SignBlock(const CKeyStore& keystore) { vector<valtype> vSolutions; txnouttype whichType; const CTxOut& txout = IsProofOfStake()? vtx[1].vout[1] : vtx[0].vout[0]; if (!Solver(txout.scriptPubKey, whichType, vSolutions)) return false; if (whichType == TX_PUBKEY) { // Sign const valtype& vchPubKey = vSolutions[0]; CKey key; if (!keystore.GetKey(Hash160(vchPubKey), key)) return false; if (key.GetPubKey() != vchPubKey) return false; return key.Sign(GetHash(), vchBlockSig); } else if (whichType == TX_SCRIPTHASH) { CScript subscript; if (!keystore.GetCScript(CScriptID(uint160(vSolutions[0])), subscript)) return false; if (!Solver(subscript, whichType, vSolutions)) return false; if (whichType != TX_COLDMINTING) return false; CKey key; if (!keystore.GetKey(uint160(vSolutions[0]), key)) return false; return key.Sign(GetHash(), vchBlockSig); } return false; } // ppcoin: check block signature bool CBlock::CheckBlockSignature() const { if (GetHash() == GENESIS_HASH) return vchBlockSig.empty(); vector<valtype> vSolutions; txnouttype whichType; const CTxOut& txout = IsProofOfStake()? vtx[1].vout[1] : vtx[0].vout[0]; if (!Solver(txout.scriptPubKey, whichType, vSolutions)) return false; if (whichType == TX_PUBKEY) { const valtype& vchPubKey = vSolutions[0]; CKey key; if (!key.SetPubKey(vchPubKey)) return false; if (vchBlockSig.empty()) return false; return key.Verify(GetHash(), vchBlockSig); } else if (whichType == TX_SCRIPTHASH) { // Output is a pay-to-script-hash // Only allowed with cold minting if (!IsProofOfStake()) return false; // CoinStake scriptSig should contain 3 pushes: the signature, the pubkey and the cold minting script CScript scriptSig = vtx[1].vin[0].scriptSig; if (!scriptSig.IsPushOnly()) return false; vector<vector<unsigned char> > stack; if (!EvalScript(stack, scriptSig, CTransaction(), 0, 0)) return false; if (stack.size() != 3) return false; // Verify the script is a cold minting script const valtype& scriptSerialized = stack.back(); CScript script(scriptSerialized.begin(), scriptSerialized.end()); if (!Solver(script, whichType, vSolutions)) return false; if (whichType != TX_COLDMINTING) return false; // Verify the scriptSig pubkey matches the minting key valtype& vchPubKey = stack[1]; if (Hash160(vchPubKey) != uint160(vSolutions[0])) return false; // Verify the block signature with the minting key CKey key; if (!key.SetPubKey(vchPubKey)) return false; if (vchBlockSig.empty()) return false; return key.Verify(GetHash(), vchBlockSig); } return false; } // ppcoin: entropy bit for stake modifier if chosen by modifier unsigned int CBlock::GetStakeEntropyBit() const { unsigned int nEntropyBit = 0; nEntropyBit = ((GetHash().Get64()) & 1llu); // last bit of block hash if (fDebug && GetBoolArg("-printstakemodifier")) printf("GetStakeEntropyBit(v0.4+): nTime=%u hashBlock=%s entropybit=%d\n", nTime, GetHash().ToString().c_str(), nEntropyBit); return nEntropyBit; } bool CheckDiskSpace(uint64 nAdditionalBytes) { uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available; // Check for 15MB because database could create another 10MB log file at any time if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes) { fShutdown = true; string strMessage = _("Warning: Disk space is low"); strMiscWarning = strMessage; printf("*** %s\n", strMessage.c_str()); ThreadSafeMessageBox(strMessage, COIN_NAME, wxOK | wxICON_EXCLAMATION | wxMODAL); StartShutdown(); return false; } return true; } FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode) { if (nFile == static_cast<unsigned int>(-1)) return NULL; FILE* file = fopen((GetDataDir() / strprintf("blk%04d.dat", nFile)).string().c_str(), pszMode); if (!file) return NULL; if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w')) { if (fseek(file, nBlockPos, SEEK_SET) != 0) { fclose(file); return NULL; } } return file; } static unsigned int nCurrentBlockFile = 1; FILE* AppendBlockFile(unsigned int& nFileRet) { nFileRet = 0; INFINITE_LOOP { FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab"); if (!file) return NULL; if (fseek(file, 0, SEEK_END) != 0) return NULL; // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB if (ftell(file) < 0x7F000000 - MAX_SIZE) { nFileRet = nCurrentBlockFile; return file; } fclose(file); nCurrentBlockFile++; } } bool LoadBlockIndex(bool fAllowNew) { // // Load block index // CTxDB txdb("cr"); if (!txdb.LoadBlockIndex()) return false; txdb.Close(); // // Init with genesis block // if (mapBlockIndex.empty()) { if (!fAllowNew) return false; // Genesis Block: // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1) // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0) // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73) // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B) // vMerkleTree: 4a5e1e const char* pszTimestamp = GENESIS_IDENT; CTransaction txNew; txNew.nTime = GENESIS_TX_TIME; txNew.vin.resize(1); txNew.vout.resize(1); txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); txNew.vout[0].SetEmpty(); CBlock block; block.vtx.push_back(txNew); block.hashPrevBlock = 0; block.hashMerkleRoot = block.BuildMerkleTree(); block.nVersion = GENESIS_BLOCK_VERSION; block.nTime = GENESIS_BLOCK_TIME; block.nBits = POW_INITIAL_TARGET.GetCompact(); block.nNonce = GENESIS_BLOCK_NONCE; printf("target : %s\n", POW_INITIAL_TARGET.getuint256().ToString().c_str()); printf("nBits : %08X\n", block.nBits); printf("expected genesis hash : %s\n", GENESIS_HASH.ToString().c_str()); printf("true genesis hash : %s\n", block.GetHash().ToString().c_str()); // If genesis block hash does not match, then generate new genesis hash. if (block.GetHash() != GENESIS_HASH || !CheckProofOfWork(block.GetHash(), block.nBits, false)) { printf("\n"); printf("FATAL ERROR: The genesis block is invalid.\n"); printf("Please notify the coins maintainers at " COIN_BUGTRACKER ".\n"); printf("If you're working on an Altcoin, we suggest you to use the following parameters as new genesis (wait a bit):\n"); // This will figure out a valid hash and Nonce if you're // creating a different genesis block: while (!CheckProofOfWork(block.GetHash(), block.nBits, false)) { if ((block.nNonce & 0xFFF) == 0) printf("Trying nonce %08X and above...\n", block.nNonce); ++block.nNonce; if (block.nNonce == 0) { printf("NONCE WRAPPED, incrementing time\n"); ++block.nTime; } } printf("A matching block has been found, with the following parameters:\n"); printf(" - GENESIS_MERKLE_HASH : %s\n", block.hashMerkleRoot.ToString().c_str()); printf(" - GENESIS_HASH : %s\n", block.GetHash().ToString().c_str()); printf(" - GENESIS_TIME : %u\n", block.nTime); printf(" - GENESIS_NONCE : %u\n", block.nNonce); std::exit( 1 ); } //// debug print assert(block.hashMerkleRoot == GENESIS_MERKLE_HASH); assert(block.GetHash() == GENESIS_HASH); assert(block.CheckBlock()); // Start new block file unsigned int nFile; unsigned int nBlockPos; if (!block.WriteToDisk(nFile, nBlockPos)) return error("LoadBlockIndex() : writing genesis block to disk failed"); if (!block.AddToBlockIndex(nFile, nBlockPos)) return error("LoadBlockIndex() : genesis block not accepted"); // ppcoin: initialize synchronized checkpoint if (!Checkpoints::WriteSyncCheckpoint(GENESIS_HASH)) { return error("LoadBlockIndex() : failed to init sync checkpoint"); } } // ppcoin: if checkpoint master key changed must reset sync-checkpoint { CTxDB txdb; string strPubKey = ""; if (!txdb.ReadCheckpointPubKey(strPubKey) || strPubKey != CHECKPOINT_PUBLIC_KEY) { // write checkpoint master key to db txdb.TxnBegin(); if (!txdb.WriteCheckpointPubKey(CHECKPOINT_PUBLIC_KEY)) return error("LoadBlockIndex() : failed to write new checkpoint master key to db"); if (!txdb.TxnCommit()) return error("LoadBlockIndex() : failed to commit new checkpoint master key to db"); if (!Checkpoints::ResetSyncCheckpoint()) return error("LoadBlockIndex() : failed to reset sync-checkpoint"); } txdb.Close(); } return true; } void PrintBlockTree() { // precompute tree structure map<CBlockIndex*, vector<CBlockIndex*> > mapNext; for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi) { CBlockIndex* pindex = (*mi).second; mapNext[pindex->pprev].push_back(pindex); // test //while (rand() % 3 == 0) // mapNext[pindex->pprev].push_back(pindex); } vector<pair<int, CBlockIndex*> > vStack; vStack.push_back(make_pair(0, pindexGenesisBlock)); int nPrevCol = 0; while (!vStack.empty()) { int nCol = vStack.back().first; CBlockIndex* pindex = vStack.back().second; vStack.pop_back(); // print split or gap if (nCol > nPrevCol) { for (int i = 0; i < nCol-1; i++) printf("| "); printf("|\\\n"); } else if (nCol < nPrevCol) { for (int i = 0; i < nCol; i++) printf("| "); printf("|\n"); } nPrevCol = nCol; // print columns for (int i = 0; i < nCol; i++) printf("| "); // print item CBlock block; block.ReadFromDisk(pindex); printf("%d (%u,%u) %s %08lx %s mint %7s tx %d", pindex->nHeight, pindex->nFile, pindex->nBlockPos, block.GetHash().ToString().c_str(), block.nBits, DateTimeStrFormat(block.GetBlockTime()).c_str(), FormatMoney(pindex->nMint).c_str(), block.vtx.size()); PrintWallets(block); // put the main timechain first vector<CBlockIndex*>& vNext = mapNext[pindex]; for (unsigned int i = 0; i < vNext.size(); i++) { if (vNext[i]->pnext) { swap(vNext[0], vNext[i]); break; } } // iterate children for (unsigned int i = 0; i < vNext.size(); i++) vStack.push_back(make_pair(nCol+i, vNext[i])); } } ////////////////////////////////////////////////////////////////////////////// // // CAlert // map<uint256, CAlert> mapAlerts; CCriticalSection cs_mapAlerts; static string strMintMessage = _("Warning: Minting suspended due to locked wallet."); static string strMintWarning; string GetWarnings(string strFor) { int nPriority = 0; string strStatusBar; string strRPC; if (GetBoolArg("-testsafemode")) strRPC = "test"; // ppcoin: wallet lock warning for minting if (strMintWarning != "") { nPriority = 0; strStatusBar = strMintWarning; } // Misc warnings like out of disk space and clock is wrong if (strMiscWarning != "") { nPriority = 1000; strStatusBar = strMiscWarning; } // ppcoin: if detected invalid checkpoint enter safe mode if (Checkpoints::hashInvalidCheckpoint != 0) { nPriority = 3000; strStatusBar = strRPC = "Warning: An invalid checkpoint has been found! Displayed transactions may not be correct! You may need to upgrade, and/or notify developers of the issue."; } // Alerts { LOCK(cs_mapAlerts); BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) { const CAlert& alert = item.second; if (alert.AppliesToMe() && alert.nPriority > nPriority) { nPriority = alert.nPriority; strStatusBar = alert.strStatusBar; if (nPriority > 1000) { strRPC = strStatusBar; // ppcoin: safe mode for high alert } } } } if (strFor == "statusbar") return strStatusBar; else if (strFor == "rpc") return strRPC; assert(!"GetWarnings() : invalid parameter"); return "error"; } bool CAlert::ProcessAlert() { if (!CheckSignature()) return false; if (!IsInEffect()) return false; { LOCK(cs_mapAlerts); // Cancel previous alerts for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();) { const CAlert& alert = (*mi).second; if (Cancels(alert)) { printf("cancelling alert %d\n", alert.nID); mapAlerts.erase(mi++); } else if (!alert.IsInEffect()) { printf("expiring alert %d\n", alert.nID); mapAlerts.erase(mi++); } else mi++; } // Check if this alert has been cancelled BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) { const CAlert& alert = item.second; if (alert.Cancels(*this)) { printf("alert already cancelled by %d\n", alert.nID); return false; } } // Add to mapAlerts mapAlerts.insert(make_pair(GetHash(), *this)); } printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe()); MainFrameRepaint(); return true; } ////////////////////////////////////////////////////////////////////////////// // // Messages // bool static AlreadyHave(CTxDB& txdb, const CInv& inv) { switch (inv.type) { case MSG_TX: { bool txInMap = false; { LOCK(mempool.cs); txInMap = (mempool.exists(inv.hash)); } return txInMap || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash); } case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash); } // Don't know what it is, just say we already got one return true; } bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv) { static map<CService, CPubKey> mapReuseKey; RandAddSeedPerfmon(); if (fDebug) { printf("%s ", DateTimeStrFormat(GetTime()).c_str()); printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size()); } if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0) { printf("dropmessagestest DROPPING RECV MESSAGE\n"); return true; } if (strCommand == "version") { // Each connection can only send one version message if (pfrom->nVersion != 0) { pfrom->Misbehaving(1); return false; } int64 nTime; CAddress addrMe; CAddress addrFrom; uint64 nNonce = 1; vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe; if (pfrom->nVersion < MIN_PROTO_VERSION) { // Since February 20, 2012, the protocol is initiated at version 209, // and earlier versions are no longer supported printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion); pfrom->fDisconnect = true; return false; } if (pfrom->nVersion == 10300) pfrom->nVersion = 300; if (!vRecv.empty()) vRecv >> addrFrom >> nNonce; if (!vRecv.empty()) vRecv >> pfrom->strSubVer; if (!vRecv.empty()) vRecv >> pfrom->nStartingHeight; // Disconnect if we connected to ourself if (nNonce == nLocalHostNonce && nNonce > 1) { printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str()); pfrom->fDisconnect = true; return true; } // ppcoin: record my external IP reported by peer if (addrFrom.IsRoutable() && addrMe.IsRoutable()) addrSeenByPeer = addrMe; // Be shy and don't send version until we hear if (pfrom->fInbound) pfrom->PushVersion(); pfrom->fClient = !(pfrom->nServices & NODE_NETWORK); AddTimeData(pfrom->addr, nTime); // Change version pfrom->PushMessage("verack"); pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION)); if (!pfrom->fInbound) { // Advertise our address if (!fNoListen && !fUseProxy && addrLocalHost.IsRoutable() && !IsInitialBlockDownload()) { CAddress addr(addrLocalHost); addr.nTime = GetAdjustedTime(); pfrom->PushAddress(addr); } // Get recent addresses if (pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000) { pfrom->PushMessage("getaddr"); pfrom->fGetAddr = true; } addrman.Good(pfrom->addr); } else { if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom) { addrman.Add(addrFrom, addrFrom); addrman.Good(addrFrom); } } // Ask the first connected node for block updates static int nAskedForBlocks = 0; if (!pfrom->fClient && (pfrom->nVersion < NOBLKS_VERSION_START || pfrom->nVersion >= NOBLKS_VERSION_END)) { nAskedForBlocks++; pfrom->PushGetBlocks(pindexBest, uint256(0)); } // Relay alerts { LOCK(cs_mapAlerts); BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) item.second.RelayTo(pfrom); } // ppcoin: relay sync-checkpoint { LOCK(Checkpoints::cs_hashSyncCheckpoint); if (!Checkpoints::checkpointMessage.IsNull()) Checkpoints::checkpointMessage.RelayTo(pfrom); } pfrom->fSuccessfullyConnected = true; printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight); cPeerBlockCounts.input(pfrom->nStartingHeight); // ppcoin: ask for pending sync-checkpoint if any if (!IsInitialBlockDownload()) Checkpoints::AskForPendingSyncCheckpoint(pfrom); } else if (pfrom->nVersion == 0) { // Must have a version message before anything else pfrom->Misbehaving(1); return false; } else if (strCommand == "verack") { pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION)); } else if (strCommand == "addr") { vector<CAddress> vAddr; vRecv >> vAddr; // Don't want addr from older versions unless seeding if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000) return true; if (vAddr.size() > 1000) { pfrom->Misbehaving(20); return error("message addr size() = %d", vAddr.size()); } // Store the new addresses int64 nNow = GetAdjustedTime(); int64 nSince = nNow - 10 * 60; BOOST_FOREACH(CAddress& addr, vAddr) { if (fShutdown) return true; // ignore IPv6 for now, since it isn't implemented anyway if (!addr.IsIPv4()) continue; if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60) addr.nTime = nNow - 5 * 24 * 60 * 60; pfrom->AddAddressKnown(addr); if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable()) { // Relay to a limited number of other nodes { LOCK(cs_vNodes); // Use deterministic randomness to send to the same nodes for 24 hours // at a time so the setAddrKnowns of the chosen nodes prevent repeats static uint256 hashSalt; if (hashSalt == 0) hashSalt = GetRandHash(); int64 hashAddr = addr.GetHash(); uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60)); hashRand = Hash(BEGIN(hashRand), END(hashRand)); multimap<uint256, CNode*> mapMix; BOOST_FOREACH(CNode* pnode, vNodes) { if (pnode->nVersion < CADDR_TIME_VERSION) continue; unsigned int nPointer; memcpy(&nPointer, &pnode, sizeof(nPointer)); uint256 hashKey = hashRand ^ nPointer; hashKey = Hash(BEGIN(hashKey), END(hashKey)); mapMix.insert(make_pair(hashKey, pnode)); } int nRelayNodes = 2; for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi) ((*mi).second)->PushAddress(addr); } } } addrman.Add(vAddr, pfrom->addr, 2 * 60 * 60); if (vAddr.size() < 1000) pfrom->fGetAddr = false; } else if (strCommand == "inv") { vector<CInv> vInv; vRecv >> vInv; if (vInv.size() > 50000) { pfrom->Misbehaving(20); return error("message inv size() = %d", vInv.size()); } // find last block in inv vector unsigned int nLastBlock = (unsigned int)(-1); for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) { if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) { nLastBlock = vInv.size() - 1 - nInv; break; } } CTxDB txdb("r"); for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) { const CInv &inv = vInv[nInv]; if (fShutdown) return true; pfrom->AddInventoryKnown(inv); bool fAlreadyHave = AlreadyHave(txdb, inv); if (fDebug) printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new"); if (!fAlreadyHave) { pfrom->AskFor(inv); } else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) { pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash])); } else if (nInv == nLastBlock) { // In case we are on a very long side-chain, it is possible that we already have // the last block in an inv bundle sent in response to getblocks. Try to detect // this situation and push another getblocks to continue. std::vector<CInv> vGetData(1,inv); pfrom->PushGetBlocks(mapBlockIndex.at(inv.hash), uint256(0)); if (fDebug) { printf("force request: %s\n", inv.ToString().c_str()); } } // Track requests for our stuff Inventory(inv.hash); } } else if (strCommand == "getdata") { vector<CInv> vInv; vRecv >> vInv; if (vInv.size() > 50000) { pfrom->Misbehaving(20); return error("message getdata size() = %d", vInv.size()); } BOOST_FOREACH(const CInv& inv, vInv) { if (fShutdown) return true; printf("received getdata for: %s\n", inv.ToString().c_str()); if (inv.type == MSG_BLOCK) { // Send block from disk map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash); if (mi != mapBlockIndex.end()) { CBlock block; block.ReadFromDisk((*mi).second); pfrom->PushMessage("block", block); // Trigger them to send a getblocks request for the next batch of inventory if (inv.hash == pfrom->hashContinue) { // Bypass PushInventory, this must send even if redundant, // and we want it right after the last block so they don't // wait for other stuff first. // ppcoin: send latest proof-of-work block to allow the // download node to accept as orphan (proof-of-stake // block might be rejected by stake connection check) vector<CInv> vInv; vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash())); pfrom->PushMessage("inv", vInv); pfrom->hashContinue = 0; } } } else if (inv.IsKnownType()) { // Send stream from relay memory { LOCK(cs_mapRelay); map<CInv, CDataStream>::iterator mi = mapRelay.find(inv); if (mi != mapRelay.end()) pfrom->PushMessage(inv.GetCommand(), (*mi).second); } } // Track requests for our stuff Inventory(inv.hash); } } else if (strCommand == "getblocks") { CBlockLocator locator; uint256 hashStop; vRecv >> locator >> hashStop; // Find the last block the caller has in the main chain CBlockIndex* pindex = locator.GetBlockIndex(); // Send the rest of the chain if (pindex) pindex = pindex->pnext; int nLimit = 500 + locator.GetDistanceBack(); unsigned int nBytes = 0; printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit); for (; pindex; pindex = pindex->pnext) { if (pindex->GetBlockHash() == hashStop) { printf(" getblocks stopping at %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes); // ppcoin: tell downloading node about the latest block if it's // without risk being rejected due to stake connection check if (hashStop != hashBestChain && pindex->GetBlockTime() + STAKE_MIN_AGE > pindexBest->GetBlockTime()) pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain)); break; } pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash())); CBlock block; block.ReadFromDisk(pindex, true); nBytes += block.GetSerializeSize(SER_NETWORK, PROTOCOL_VERSION); if (--nLimit <= 0 || nBytes >= SendBufferSize()/2) { // When this block is requested, we'll send an inv that'll make them // getblocks the next batch of inventory. printf(" getblocks stopping at limit %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes); pfrom->hashContinue = pindex->GetBlockHash(); break; } } } else if (strCommand == "getheaders") { CBlockLocator locator; uint256 hashStop; vRecv >> locator >> hashStop; CBlockIndex* pindex = NULL; if (locator.IsNull()) { // If locator is null, return the hashStop block map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop); if (mi == mapBlockIndex.end()) return true; pindex = (*mi).second; } else { // Find the last block the caller has in the main chain pindex = locator.GetBlockIndex(); if (pindex) pindex = pindex->pnext; } vector<CBlock> vHeaders; int nLimit = 2000; printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str()); for (; pindex; pindex = pindex->pnext) { vHeaders.push_back(pindex->GetBlockHeader()); if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop) break; } pfrom->PushMessage("headers", vHeaders); } else if (strCommand == "tx") { vector<uint256> vWorkQueue; vector<uint256> vEraseQueue; CDataStream vMsg(vRecv); CTxDB txdb("r"); CTransaction tx; vRecv >> tx; CInv inv(MSG_TX, tx.GetHash()); pfrom->AddInventoryKnown(inv); bool fMissingInputs = false; if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs)) { SyncWithWallets(tx, NULL, true); RelayMessage(inv, vMsg); mapAlreadyAskedFor.erase(inv); vWorkQueue.push_back(inv.hash); vEraseQueue.push_back(inv.hash); // Recursively process any orphan transactions that depended on this one for (unsigned int i = 0; i < vWorkQueue.size(); i++) { uint256 hashPrev = vWorkQueue[i]; for (map<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin(); mi != mapOrphanTransactionsByPrev[hashPrev].end(); ++mi) { const CDataStream& vMsg = *((*mi).second); CTransaction tx; CDataStream(vMsg) >> tx; CInv inv(MSG_TX, tx.GetHash()); bool fMissingInputs2 = false; if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs2)) { printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str()); SyncWithWallets(tx, NULL, true); RelayMessage(inv, vMsg); mapAlreadyAskedFor.erase(inv); vWorkQueue.push_back(inv.hash); vEraseQueue.push_back(inv.hash); } else if (!fMissingInputs2) { // invalid orphan vEraseQueue.push_back(inv.hash); printf(" removed invalid orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str()); } } } BOOST_FOREACH(uint256 hash, vEraseQueue) EraseOrphanTx(hash); } else if (fMissingInputs) { AddOrphanTx(vMsg); // DoS prevention: do not allow mapOrphanTransactions to grow unbounded unsigned int nEvicted = LimitOrphanTxSize(MAX_BLOCK_ORPHAN_TX); if (nEvicted > 0) printf("mapOrphan overflow, removed %u tx\n", nEvicted); } if (tx.nDoS) pfrom->Misbehaving(tx.nDoS); } else if (strCommand == "block") { CBlock block; vRecv >> block; printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str()); // block.print(); CInv inv(MSG_BLOCK, block.GetHash()); pfrom->AddInventoryKnown(inv); if (ProcessBlock(pfrom, &block)) mapAlreadyAskedFor.erase(inv); if (block.nDoS) pfrom->Misbehaving(block.nDoS); } else if (strCommand == "getaddr") { pfrom->vAddrToSend.clear(); vector<CAddress> vAddr = addrman.GetAddr(); BOOST_FOREACH(const CAddress &addr, vAddr) pfrom->PushAddress(addr); } else if (strCommand == "checkorder") { uint256 hashReply; vRecv >> hashReply; if (!GetBoolArg("-allowreceivebyip")) { pfrom->PushMessage("reply", hashReply, (int)2, string("")); return true; } CWalletTx order; vRecv >> order; /// we have a chance to check the order here // Keep giving the same key to the same ip until they use it if (!mapReuseKey.count(pfrom->addr)) pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true); // Send back approval of order and pubkey to use CScript scriptPubKey; scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG; pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey); } else if (strCommand == "reply") { uint256 hashReply; vRecv >> hashReply; CRequestTracker tracker; { LOCK(pfrom->cs_mapRequests); map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply); if (mi != pfrom->mapRequests.end()) { tracker = (*mi).second; pfrom->mapRequests.erase(mi); } } if (!tracker.IsNull()) tracker.fn(tracker.param1, vRecv); } else if (strCommand == "ping") { if (pfrom->nVersion > BIP0031_VERSION) { uint64 nonce = 0; vRecv >> nonce; // Echo the message back with the nonce. This allows for two useful features: // // 1) A remote node can quickly check if the connection is operational // 2) Remote nodes can measure the latency of the network thread. If this node // is overloaded it won't respond to pings quickly and the remote node can // avoid sending us more work, like chain download requests. // // The nonce stops the remote getting confused between different pings: without // it, if the remote node sends a ping once per second and this node takes 5 // seconds to respond to each, the 5th ping the remote sends would appear to // return very quickly. pfrom->PushMessage("pong", nonce); } } else if (strCommand == "alert") { CAlert alert; vRecv >> alert; if (alert.ProcessAlert()) { // Relay pfrom->setKnown.insert(alert.GetHash()); { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) alert.RelayTo(pnode); } } } else if (strCommand == "checkpoint") { CSyncCheckpoint checkpoint; vRecv >> checkpoint; if (checkpoint.ProcessSyncCheckpoint(pfrom)) { // Relay pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint; LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) checkpoint.RelayTo(pnode); } } else { // Ignore unknown commands for extensibility } // Update the last seen time for this node's address if (pfrom->fNetworkNode) if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping") AddressCurrentlyConnected(pfrom->addr); return true; } bool ProcessMessages(CNode* pfrom) { CDataStream& vRecv = pfrom->vRecv; if (vRecv.empty()) return true; //if (fDebug) // printf("ProcessMessages(%u bytes)\n", vRecv.size()); // // Message format // (4) message start // (12) command // (4) size // (4) checksum // (x) data // unsigned char pchMessageStart[4]; GetMessageStart(pchMessageStart); static int64 nTimeLastPrintMessageStart = 0; if (fDebug && GetBoolArg("-printmessagestart") && nTimeLastPrintMessageStart + 30 < GetAdjustedTime()) { string strMessageStart((const char *)pchMessageStart, sizeof(pchMessageStart)); vector<unsigned char> vchMessageStart(strMessageStart.begin(), strMessageStart.end()); printf("ProcessMessages : AdjustedTime=%"PRI64d" MessageStart=%s\n", GetAdjustedTime(), HexStr(vchMessageStart).c_str()); nTimeLastPrintMessageStart = GetAdjustedTime(); } INFINITE_LOOP { // Safe guards to prevent the node to ignore a requested shutdown // in case of long processing if (fRequestShutdown) { StartShutdown(); return true; } // Scan for message start CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart)); int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader()); if (vRecv.end() - pstart < nHeaderSize) { if ((int)vRecv.size() > nHeaderSize) { printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n"); vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize); } break; } if (pstart - vRecv.begin() > 0) printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin()); vRecv.erase(vRecv.begin(), pstart); // Read header vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize); CMessageHeader hdr; vRecv >> hdr; if (!hdr.IsValid()) { printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str()); continue; } string strCommand = hdr.GetCommand(); // Message size unsigned int nMessageSize = hdr.nMessageSize; if (nMessageSize > MAX_SIZE) { printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize); continue; } if (nMessageSize > vRecv.size()) { // Rewind and wait for rest of message vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end()); break; } // Checksum uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize); unsigned int nChecksum = 0; memcpy(&nChecksum, &hash, sizeof(nChecksum)); if (nChecksum != hdr.nChecksum) { printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n", strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum); continue; } // Copy message to its own buffer CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion); vRecv.ignore(nMessageSize); // Process message bool fRet = false; try { { LOCK(cs_main); fRet = ProcessMessage(pfrom, strCommand, vMsg); } if (fShutdown) return true; } catch (std::ios_base::failure& e) { if (strstr(e.what(), "end of data")) { // Allow exceptions from underlength message on vRecv printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what()); } else if (strstr(e.what(), "size too large")) { // Allow exceptions from overlong size printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what()); } else { PrintExceptionContinue(&e, "ProcessMessages()"); } } catch (std::exception& e) { PrintExceptionContinue(&e, "ProcessMessages()"); } catch (...) { PrintExceptionContinue(NULL, "ProcessMessages()"); } if (!fRet) printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize); } vRecv.Compact(); return true; } bool SendMessages(CNode* pto, bool fSendTrickle) { TRY_LOCK(cs_main, lockMain); if (lockMain) { // Don't send anything until we get their version message if (pto->nVersion == 0) return true; // Keep-alive ping. We send a nonce of zero because we don't use it anywhere // right now. if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) { uint64 nonce = 0; if (pto->nVersion > BIP0031_VERSION) pto->PushMessage("ping", nonce); else pto->PushMessage("ping"); } // Resend wallet transactions that haven't gotten in a block yet ResendWalletTransactions(); // Address refresh broadcast static int64 nLastRebroadcast; if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60)) { { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { // Periodically clear setAddrKnown to allow refresh broadcasts if (nLastRebroadcast) pnode->setAddrKnown.clear(); // Rebroadcast our address if (!fNoListen && !fUseProxy && addrLocalHost.IsRoutable()) { CAddress addr(addrLocalHost); addr.nTime = GetAdjustedTime(); pnode->PushAddress(addr); } } } nLastRebroadcast = GetTime(); } // // Message: addr // if (fSendTrickle) { vector<CAddress> vAddr; vAddr.reserve(pto->vAddrToSend.size()); BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend) { // returns true if wasn't already contained in the set if (pto->setAddrKnown.insert(addr).second) { vAddr.push_back(addr); // receiver rejects addr messages larger than 1000 if (vAddr.size() >= 1000) { pto->PushMessage("addr", vAddr); vAddr.clear(); } } } pto->vAddrToSend.clear(); if (!vAddr.empty()) pto->PushMessage("addr", vAddr); } // // Message: inventory // vector<CInv> vInv; vector<CInv> vInvWait; { LOCK(pto->cs_inventory); vInv.reserve(pto->vInventoryToSend.size()); vInvWait.reserve(pto->vInventoryToSend.size()); BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend) { if (pto->setInventoryKnown.count(inv)) continue; // trickle out tx inv to protect privacy if (inv.type == MSG_TX && !fSendTrickle) { // 1/4 of tx invs blast to all immediately static uint256 hashSalt; if (hashSalt == 0) hashSalt = GetRandHash(); uint256 hashRand = inv.hash ^ hashSalt; hashRand = Hash(BEGIN(hashRand), END(hashRand)); bool fTrickleWait = ((hashRand & 3) != 0); // always trickle our own transactions if (!fTrickleWait) { CWalletTx wtx; if (GetTransaction(inv.hash, wtx)) if (wtx.fFromMe) fTrickleWait = true; } if (fTrickleWait) { vInvWait.push_back(inv); continue; } } // returns true if wasn't already contained in the set if (pto->setInventoryKnown.insert(inv).second) { vInv.push_back(inv); if (vInv.size() >= 1000) { pto->PushMessage("inv", vInv); vInv.clear(); } } } pto->vInventoryToSend = vInvWait; } if (!vInv.empty()) pto->PushMessage("inv", vInv); // // Message: getdata // vector<CInv> vGetData; int64 nNow = GetTime() * 1000000; CTxDB txdb("r"); while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow) { const CInv& inv = (*pto->mapAskFor.begin()).second; if (!AlreadyHave(txdb, inv)) { printf("sending getdata: %s\n", inv.ToString().c_str()); vGetData.push_back(inv); if (vGetData.size() >= 1000) { pto->PushMessage("getdata", vGetData); vGetData.clear(); } } mapAlreadyAskedFor[inv] = nNow; pto->mapAskFor.erase(pto->mapAskFor.begin()); } if (!vGetData.empty()) pto->PushMessage("getdata", vGetData); } return true; } ////////////////////////////////////////////////////////////////////////////// // // BitcoinMiner // int static FormatHashBlocks(void* pbuffer, unsigned int len) { unsigned char* pdata = (unsigned char*)pbuffer; unsigned int blocks = 1 + ((len + 8) / 64); unsigned char* pend = pdata + 64 * blocks; memset(pdata + len, 0, 64 * blocks - len); pdata[len] = 0x80; unsigned int bits = len * 8; pend[-1] = (bits >> 0) & 0xff; pend[-2] = (bits >> 8) & 0xff; pend[-3] = (bits >> 16) & 0xff; pend[-4] = (bits >> 24) & 0xff; return blocks; } static const unsigned int pSHA256InitState[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19}; void SHA256Transform(void* pstate, void* pinput, const void* pinit) { SHA256_CTX ctx; unsigned char data[64]; SHA256_Init(&ctx); for (int i = 0; i < 16; i++) ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]); for (int i = 0; i < 8; i++) ctx.h[i] = ((uint32_t*)pinit)[i]; SHA256_Update(&ctx, data, sizeof(data)); for (int i = 0; i < 8; i++) ((uint32_t*)pstate)[i] = ctx.h[i]; } // Some explaining would be appreciated class COrphan { public: CTransaction* ptx; set<uint256> setDependsOn; double dPriority; COrphan(CTransaction* ptxIn) { ptx = ptxIn; dPriority = 0; } void print() const { printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority); BOOST_FOREACH(uint256 hash, setDependsOn) printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str()); } }; uint64 nLastBlockTx = 0; uint64 nLastBlockSize = 0; int64 nLastCoinStakeSearchInterval = 0; // CreateNewBlock: // fProofOfStake: try (best effort) to make a proof-of-stake block CBlock* CreateNewBlock(CReserveKey& reservekey, CWallet* pwallet, bool fProofOfStake) { // Create new block auto_ptr<CBlock> pblock(new CBlock()); if (!pblock.get()) return NULL; // Create coinbase tx CTransaction txNew; txNew.vin.resize(1); txNew.vin[0].prevout.SetNull(); txNew.vout.resize(1); txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG; // Add our coinbase tx as first transaction pblock->vtx.push_back(txNew); // ppcoin: if coinstake available add coinstake tx static int64 nLastCoinStakeSearchTime = GetAdjustedTime(); // only initialized at startup CBlockIndex* pindexPrev = pindexBest; if (fProofOfStake) // attemp to find a coinstake { pblock->nBits = GetNextTargetRequired(pindexPrev, true); CTransaction txCoinStake; int64 nSearchTime = txCoinStake.nTime; // search to current time if (nSearchTime > nLastCoinStakeSearchTime) { if (pwallet->CreateCoinStake(*pwallet, pblock->nBits, nSearchTime-nLastCoinStakeSearchTime, txCoinStake)) { if (txCoinStake.nTime >= max(pindexPrev->GetMedianTimePast()+1, pindexPrev->GetBlockTime() - MAX_CLOCK_DRIFT)) { // make sure coinstake would meet timestamp protocol // as it would be the same as the block timestamp pblock->vtx[0].vout[0].SetEmpty(); pblock->vtx[0].nTime = txCoinStake.nTime; pblock->vtx.push_back(txCoinStake); } } nLastCoinStakeSearchInterval = nSearchTime - nLastCoinStakeSearchTime; nLastCoinStakeSearchTime = nSearchTime; } } pblock->nBits = GetNextTargetRequired(pindexPrev, pblock->IsProofOfStake()); // Collect memory pool transactions into the block int64 nFees = 0; { LOCK2(cs_main, mempool.cs); CTxDB txdb("r"); // Priority order to process transactions list<COrphan> vOrphan; // list memory doesn't move map<uint256, vector<COrphan*> > mapDependers; multimap<double, CTransaction*> mapPriority; for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi) { CTransaction& tx = (*mi).second; if (tx.IsCoinBase() || tx.IsCoinStake() || !tx.IsFinal()) continue; COrphan* porphan = NULL; double dPriority = 0; BOOST_FOREACH(const CTxIn& txin, tx.vin) { // Read prev transaction CTransaction txPrev; CTxIndex txindex; if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex)) { // Has to wait for dependencies if (!porphan) { // Use list for automatic deletion vOrphan.push_back(COrphan(&tx)); porphan = &vOrphan.back(); } mapDependers[txin.prevout.hash].push_back(porphan); porphan->setDependsOn.insert(txin.prevout.hash); continue; } int64 nValueIn = txPrev.vout[txin.prevout.n].nValue; // Read block header int nConf = txindex.GetDepthInMainChain(); dPriority += (double)nValueIn * nConf; if (fDebug && GetBoolArg("-printpriority")) printf("priority nValueIn=%-12"PRI64d" nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority); } // Priority is sum(valuein * age) / txsize dPriority /= ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); if (porphan) porphan->dPriority = dPriority; else mapPriority.insert(make_pair(-dPriority, &(*mi).second)); if (fDebug && GetBoolArg("-printpriority")) { printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str()); if (porphan) porphan->print(); printf("\n"); } } // Collect transactions into block map<uint256, CTxIndex> mapTestPool; uint64 nBlockSize = 1000; uint64 nBlockTx = 0; int nBlockSigOps = 100; while (!mapPriority.empty()) { // Take highest priority transaction off priority queue CTransaction& tx = *(*mapPriority.begin()).second; mapPriority.erase(mapPriority.begin()); // Size limits unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN) continue; // Legacy limits on sigOps: unsigned int nTxSigOps = tx.GetLegacySigOpCount(); if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS) continue; // Timestamp limit if (tx.nTime > GetAdjustedTime() || (pblock->IsProofOfStake() && tx.nTime > pblock->vtx[1].nTime)) continue; // ppcoin: simplify transaction fee - allow free = false int64 nMinFee = tx.GetMinFee(nBlockSize, false, GMF_BLOCK); // Connecting shouldn't fail due to dependency on other memory pool transactions // because we're already processing them in order of dependency map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool); MapPrevTx mapInputs; bool fInvalid; if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid)) continue; int64 nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut(); if (nTxFees < nMinFee) continue; nTxSigOps += tx.GetP2SHSigOpCount(mapInputs); if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS) continue; if (!tx.ConnectInputs(txdb, mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true)) continue; mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size()); swap(mapTestPool, mapTestPoolTmp); // Added pblock->vtx.push_back(tx); nBlockSize += nTxSize; ++nBlockTx; nBlockSigOps += nTxSigOps; nFees += nTxFees; // Add transactions that depend on this one to the priority queue uint256 hash = tx.GetHash(); if (mapDependers.count(hash)) { BOOST_FOREACH(COrphan* porphan, mapDependers[hash]) { if (!porphan->setDependsOn.empty()) { porphan->setDependsOn.erase(hash); if (porphan->setDependsOn.empty()) mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx)); } } } } nLastBlockTx = nBlockTx; nLastBlockSize = nBlockSize; if (fDebug && GetBoolArg("-printpriority")) { printf("CreateNewBlock(): total size %lu\n", nBlockSize); } } if (pblock->IsProofOfWork()) pblock->vtx[0].vout[0].nValue = GetProofOfWorkReward(pindexPrev->nHeight); // Fill in header pblock->hashPrevBlock = pindexPrev->GetBlockHash(); pblock->hashMerkleRoot = pblock->BuildMerkleTree(); if (pblock->IsProofOfStake()) pblock->nTime = pblock->vtx[1].nTime; //same as coinstake timestamp pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime()); pblock->nTime = max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - MAX_CLOCK_DRIFT); if (pblock->IsProofOfWork()) pblock->UpdateTime(pindexPrev); pblock->nNonce = 0; return pblock.release(); } void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce) { // Update nExtraNonce static uint256 hashPrevBlock; if (hashPrevBlock != pblock->hashPrevBlock) { nExtraNonce = 0; hashPrevBlock = pblock->hashPrevBlock; } ++nExtraNonce; pblock->vtx[0].vin[0].scriptSig = (CScript() << pblock->nTime << CBigNum(nExtraNonce)) + COINBASE_FLAGS; assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100); pblock->hashMerkleRoot = pblock->BuildMerkleTree(); } void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1) { // // Prebuild hash buffers // struct { struct unnamed2 { int nVersion; uint256 hashPrevBlock; uint256 hashMerkleRoot; unsigned int nTime; unsigned int nBits; unsigned int nNonce; } block; unsigned char pchPadding0[64]; uint256 hash1; unsigned char pchPadding1[64]; } tmp; memset(&tmp, 0, sizeof(tmp)); tmp.block.nVersion = pblock->nVersion; tmp.block.hashPrevBlock = pblock->hashPrevBlock; tmp.block.hashMerkleRoot = pblock->hashMerkleRoot; tmp.block.nTime = pblock->nTime; tmp.block.nBits = pblock->nBits; tmp.block.nNonce = pblock->nNonce; FormatHashBlocks(&tmp.block, sizeof(tmp.block)); FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1)); // Byte swap all the input buffer for (unsigned int i = 0; i < sizeof(tmp)/4; i++) ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]); // Precalc the first half of the first hash, which stays constant SHA256Transform(pmidstate, &tmp.block, pSHA256InitState); memcpy(pdata, &tmp.block, 128); memcpy(phash1, &tmp.hash1, 64); } bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey) { uint256 hash = pblock->GetHash(); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); printf("Hash: %s\nTarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str()); if (hash > hashTarget && pblock->IsProofOfWork()) return error("BitcoinMiner : proof-of-work not meeting target"); //// debug print printf("BitcoinMiner:\n"); printf("new block found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str()); pblock->print(); printf("%s ", DateTimeStrFormat(GetTime()).c_str()); printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str()); // Found a solution { LOCK(cs_main); if (pblock->hashPrevBlock != hashBestChain) return error("BitcoinMiner : generated block is stale"); // Remove key from key pool reservekey.KeepKey(); // Track how many getdata requests this block gets { LOCK(wallet.cs_wallet); wallet.mapRequestCount[pblock->GetHash()] = 0; } // Process this block the same as if we had received it from another node if (!ProcessBlock(NULL, pblock)) return error("BitcoinMiner : ProcessBlock, block not accepted"); } return true; } void static ThreadBitcoinMiner(void* parg); bool fStaking = true; static bool fGenerateBitcoins = false; static bool fLimitProcessors = false; static int nLimitProcessors = -1; bool BitcoinMiner(CWallet *pwallet, bool fProofOfStake, uint256 * minedBlock, uint64 nTimeout) { printf("CPUMiner started for proof-of-%s (%d)\n", fProofOfStake? "stake" : "work", vnThreadsRunning[fProofOfStake? THREAD_MINTER : THREAD_MINER]); SetThreadPriority(THREAD_PRIORITY_LOWEST); uint64 nStartTime = GetTime(); // Each thread has its own key and counter CReserveKey reservekey(pwallet); unsigned int nExtraNonce = 0; while (minedBlock || fGenerateBitcoins || fProofOfStake) { if (fShutdown || (fProofOfStake && !fStaking)) return false; if (nTimeout && (GetTime() - nStartTime > nTimeout)) return false; while (vNodes.empty() || IsInitialBlockDownload()) { Sleep(1000); if (fShutdown || (fProofOfStake && !fStaking)) return false; if (!minedBlock && (!fGenerateBitcoins && !fProofOfStake)) return false; } while (pwallet->IsLocked()) { strMintWarning = strMintMessage; Sleep(1000); } strMintWarning.clear(); // // Create new block // unsigned int nTransactionsUpdatedLast = nTransactionsUpdated; CBlockIndex* pindexPrev = pindexBest; auto_ptr<CBlock> pblock(CreateNewBlock(reservekey, pwallet, fProofOfStake)); if (!pblock.get()) return false; IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce); if (fProofOfStake) { // ppcoin: if proof-of-stake block found then process block if (pblock->IsProofOfStake()) { if (!pblock->SignBlock(*pwalletMain)) { strMintWarning = strMintMessage; continue; } strMintWarning.clear(); printf("CPUMiner : proof-of-stake block found %s\n", pblock->GetHash().ToString().c_str()); SetThreadPriority(THREAD_PRIORITY_NORMAL); bool fSucceeded = CheckWork(pblock.get(), *pwalletMain, reservekey); SetThreadPriority(THREAD_PRIORITY_LOWEST); if (fSucceeded && minedBlock) { *minedBlock = pblock->GetHash(); return true; } } Sleep(500); continue; } printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size()); // // Search // int64 nStart = GetTime(); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); INFINITE_LOOP { unsigned int nHashesDone = 0; pblock->nNonce = 0; INFINITE_LOOP { if (pblock->GetHash() <= hashTarget) break; pblock->nNonce += 1; nHashesDone += 1; if ((pblock->nNonce & 0xFFFF) == 0) break; } // Check if something found if (pblock->GetHash() <= hashTarget) { if (!pblock->SignBlock(*pwalletMain)) { strMintWarning = strMintMessage; break; } else { strMintWarning = ""; } SetThreadPriority(THREAD_PRIORITY_NORMAL); bool fSucceeded = CheckWork(pblock.get(), *pwalletMain, reservekey); SetThreadPriority(THREAD_PRIORITY_LOWEST); if (fSucceeded && minedBlock) { *minedBlock = pblock->GetHash(); return true; } break; } // Meter hashes/sec static int64 nHashCounter; if (nHPSTimerStart == 0) { nHPSTimerStart = GetTimeMillis(); nHashCounter = 0; } else { nHashCounter += nHashesDone; } if (GetTimeMillis() - nHPSTimerStart > 4000) { static CCriticalSection cs; { LOCK(cs); if (GetTimeMillis() - nHPSTimerStart > 4000) { dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart); nHPSTimerStart = GetTimeMillis(); nHashCounter = 0; static int64 nLogTime; if (GetTime() - nLogTime > 30 * 60) { nLogTime = GetTime(); printf("%s ", DateTimeStrFormat(GetTime()).c_str()); printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[THREAD_MINER], dHashesPerSec/1000.0); } } } } // Check for stop or if block needs to be rebuilt if (fShutdown || (fProofOfStake && !fStaking)) return false; if (!minedBlock && !fGenerateBitcoins) return false; if (fLimitProcessors && vnThreadsRunning[THREAD_MINER] > nLimitProcessors) return false; if (vNodes.empty()) break; if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60) break; if (pindexPrev != pindexBest) break; // Update nTime every few seconds pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime()); pblock->nTime = max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - MAX_CLOCK_DRIFT); pblock->UpdateTime(pindexPrev); if (pblock->GetBlockTime() >= (int64)pblock->vtx[0].nTime + MAX_CLOCK_DRIFT) { break; // need to update coinbase timestamp } } } return false; } void static ThreadBitcoinMiner(void* parg) { CWallet* pwallet = (CWallet*)parg; try { vnThreadsRunning[THREAD_MINER]++; BitcoinMiner(pwallet, false); vnThreadsRunning[THREAD_MINER]--; } catch (std::exception& e) { vnThreadsRunning[THREAD_MINER]--; PrintException(&e, "ThreadBitcoinMiner()"); } catch (...) { vnThreadsRunning[THREAD_MINER]--; PrintException(NULL, "ThreadBitcoinMiner()"); } nHPSTimerStart = 0; if (vnThreadsRunning[THREAD_MINER] == 0) dHashesPerSec = 0; printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINER]); } void GenerateBitcoins(bool fGenerate, CWallet* pwallet) { fGenerateBitcoins = fGenerate; nLimitProcessors = GetArg("-genproclimit", -1); if (nLimitProcessors == 0) fGenerateBitcoins = false; fLimitProcessors = (nLimitProcessors != -1); if (fGenerate) { int nProcessors = boost::thread::hardware_concurrency(); printf("%d processors\n", nProcessors); if (nProcessors < 1) nProcessors = 1; if (fLimitProcessors && nProcessors > nLimitProcessors) nProcessors = nLimitProcessors; int nAddThreads = nProcessors - vnThreadsRunning[THREAD_MINER]; printf("Starting %d BitcoinMiner threads\n", nAddThreads); for (int i = 0; i < nAddThreads; i++) { if (!CreateThread(ThreadBitcoinMiner, pwallet)) printf("Error: CreateThread(ThreadBitcoinMiner) failed\n"); Sleep(10); } } }
Magicking/neucoin
src/main.cpp
C++
mit
146,265
'use strict'; console.log('TESTTTT'); var mean = require('meanio'); exports.render = function (req, res) { function isAdmin() { return req.user && req.user.roles.indexOf('admin') !== -1; } // Send some basic starting info to the view res.render('index', { user: req.user ? { name: req.user.name, _id: req.user._id, username: req.user.username, roles: req.user.roles } : {}, modules: 'ho', motti: 'motti is cool', isAdmin: 'motti', adminEnabled: isAdmin() && mean.moduleEnabled('mean-admin') }); };
mottihoresh/nodarium-web
packages/custom/nodarium/server/controllers/index.js
JavaScript
mit
627
/* concatenated from client/src/app/js/globals.js */ (function () { if (!window.console) { window.console = {}; } var m = [ "log", "info", "warn", "error", "debug", "trace", "dir", "group", "groupCollapsed", "groupEnd", "time", "timeEnd", "profile", "profileEnd", "dirxml", "assert", "count", "markTimeline", "timeStamp", "clear" ]; for (var i = 0; i < m.length; i++) { if (!window.console[m[i]]) { window.console[m[i]] = function() {}; } } _.mixin({ compactObject: function(o) { _.each(o, function(v, k) { if(!v) { delete o[k]; } }); return o; } }); })(); /* concatenated from client/src/app/js/app.js */ const mainPages = { HOME: "/", WALKS: "/walks", SOCIAL: "/social", JOIN_US: "/join-us", CONTACT_US: "/contact-us", COMMITTEE: "/committee", ADMIN: "/admin", HOW_TO: "/how-to" }; angular.module("ekwgApp", [ "btford.markdown", "ngRoute", "ngSanitize", "ui.bootstrap", "angularModalService", "btford.markdown", "mongolabResourceHttp", "ngAnimate", "ngCookies", "ngFileUpload", "ngSanitize", "ui.bootstrap", "ui.select", "angular-logger", "ezfb", "ngCsv"]) .constant("MONGOLAB_CONFIG", { trimErrorMessage: false, baseUrl: "/databases/", database: "ekwg" }) .constant("AUDIT_CONFIG", { auditSave: true, }) .constant("PAGE_CONFIG", { mainPages: mainPages }) .config(["$compileProvider", function ($compileProvider) { $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|chrome-extension|tel):/); }]) .constant("MAILCHIMP_APP_CONSTANTS", { allowSendCampaign: true, apiServer: "https://us3.admin.mailchimp.com" }) .config(["$locationProvider", function ($locationProvider) { $locationProvider.hashPrefix(""); }]) .config(["$routeProvider", "uiSelectConfig", "uibDatepickerConfig", "uibDatepickerPopupConfig", "logEnhancerProvider", function ($routeProvider, uiSelectConfig, uibDatepickerConfig, uibDatepickerPopupConfig, logEnhancerProvider) { uiSelectConfig.theme = "bootstrap"; uiSelectConfig.closeOnSelect = false; $routeProvider .when(mainPages.ADMIN + "/expenseId/:expenseId", { controller: "AdminController", templateUrl: "partials/admin/admin.html", title: "expenses" }) .when(mainPages.ADMIN + "/:area?", { controller: "AdminController", templateUrl: "partials/admin/admin.html", title: "admin" }) .when(mainPages.COMMITTEE + "/committeeFileId/:committeeFileId", { controller: "CommitteeController", templateUrl: "partials/committee/committee.html", title: "AGM and committee" }) .when(mainPages.COMMITTEE, { controller: "CommitteeController", templateUrl: "partials/committee/committee.html", title: "AGM and committee" }) .when(mainPages.HOW_TO, { controller: "HowToController", templateUrl: "partials/howTo/how-to.html", title: "How-to" }) .when("/image-editor/:imageSource", { controller: "ImageEditController", templateUrl: "partials/imageEditor/image-editor.html", title: "image editor" }) .when(mainPages.JOIN_US, { controller: "HomeController", templateUrl: "partials/joinUs/join-us.html", title: "join us" }) .when("/letterhead/:firstPart?/:secondPart", { controller: "LetterheadController", templateUrl: "partials/letterhead/letterhead.html", title: "letterhead" }) .when(mainPages.CONTACT_US, { controller: "ContactUsController", templateUrl: "partials/contactUs/contact-us.html", title: "contact us" }) .when("/links", {redirectTo: mainPages.CONTACT_US}) .when(mainPages.SOCIAL + "/socialEventId/:socialEventId", { controller: "SocialEventsController", templateUrl: "partials/socialEvents/social.html", title: "social" }) .when(mainPages.SOCIAL + "/:area?", { controller: "SocialEventsController", templateUrl: "partials/socialEvents/social.html", title: "social" }) .when(mainPages.WALKS + "/walkId/:walkId", { controller: "WalksController", templateUrl: "partials/walks/walks.html", title: "walks" }) .when(mainPages.WALKS + "/:area?", { controller: "WalksController", templateUrl: "partials/walks/walks.html", title: "walks" }) .when(mainPages.HOME, { controller: "HomeController", templateUrl: "partials/home/home.html", title: "home" }) .when("/set-password/:passwordResetId", { controller: "AuthenticationModalsController", templateUrl: "partials/home/home.html" }) .otherwise({ controller: "AuthenticationModalsController", templateUrl: "partials/home/home.html" }); uibDatepickerConfig.startingDay = 1; uibDatepickerConfig.showWeeks = false; uibDatepickerPopupConfig.datepickerPopup = "dd-MMM-yyyy"; uibDatepickerPopupConfig.formatDay = "dd"; logEnhancerProvider.datetimePattern = "hh:mm:ss"; logEnhancerProvider.prefixPattern = "%s - %s -"; }]) .run(["$log", "$rootScope", "$route", "URLService", "CommitteeConfig", "CommitteeReferenceData", function ($log, $rootScope, $route, URLService, CommitteeConfig, CommitteeReferenceData) { var logger = $log.getInstance("App.run"); $log.logLevels["App.run"] = $log.LEVEL.OFF; $rootScope.$on('$locationChangeStart', function (evt, absNewUrl, absOldUrl) { }); $rootScope.$on("$locationChangeSuccess", function (event, newUrl, absOldUrl) { if (!$rootScope.pageHistory) $rootScope.pageHistory = []; $rootScope.pageHistory.push(URLService.relativeUrl(newUrl)); logger.info("newUrl", newUrl, "$rootScope.pageHistory", $rootScope.pageHistory); }); $rootScope.$on("$routeChangeSuccess", function (currentRoute, previousRoute) { $rootScope.title = $route.current.title; }); CommitteeConfig.getConfig() .then(function (config) { angular.extend(CommitteeReferenceData, config.committee); $rootScope.$broadcast("CommitteeReferenceDataReady", CommitteeReferenceData); }); }]); /* concatenated from client/src/app/js/admin.js */ angular.module('ekwgApp') .controller('AdminController', ["$rootScope", "$scope", "LoggedInMemberService", function($rootScope, $scope, LoggedInMemberService) { function setViewPriveleges() { $scope.loggedIn = LoggedInMemberService.memberLoggedIn(); $scope.memberAdmin = LoggedInMemberService.allowMemberAdminEdits(); LoggedInMemberService.showLoginPromptWithRouteParameter('expenseId'); } setViewPriveleges(); $scope.$on('memberLoginComplete', function() { setViewPriveleges(); }); $scope.$on('memberLogoutComplete', function() { setViewPriveleges(); }); }] ); /* concatenated from client/src/app/js/authenticationModalsController.js */ angular.module('ekwgApp') .controller("AuthenticationModalsController", ["$log", "$scope", "URLService", "$location", "$routeParams", "AuthenticationModalsService", "LoggedInMemberService", function ($log, $scope, URLService, $location, $routeParams, AuthenticationModalsService, LoggedInMemberService) { var logger = $log.getInstance("AuthenticationModalsController"); $log.logLevels["AuthenticationModalsController"] = $log.LEVEL.OFF; var urlFirstSegment = URLService.relativeUrlFirstSegment(); logger.info("URLService.relativeUrl:", urlFirstSegment, "$routeParams:", $routeParams); switch (urlFirstSegment) { case "/login": return AuthenticationModalsService.showLoginDialog(); case "/logout": return LoggedInMemberService.logout(); case "/mailing-preferences": if (LoggedInMemberService.memberLoggedIn()) { return AuthenticationModalsService.showMailingPreferencesDialog(LoggedInMemberService.loggedInMember().memberId); } else { return URLService.setRoot(); } case "/forgot-password": return AuthenticationModalsService.showForgotPasswordModal(); case "/set-password": return LoggedInMemberService.getMemberByPasswordResetId($routeParams.passwordResetId) .then(function (member) { logger.info("for $routeParams.passwordResetId", $routeParams.passwordResetId, "member", member); if (_.isEmpty(member)) { return AuthenticationModalsService.showResetPasswordFailedDialog(); } else { return AuthenticationModalsService.showResetPasswordModal(member.userName) } }); default: logger.warn(URLService.relativeUrl(), "doesnt match any of the supported urls"); return URLService.setRoot(); } }] ); /* concatenated from client/src/app/js/authenticationModalsService.js */ angular.module('ekwgApp') .factory("AuthenticationModalsService", ["$log", "ModalService", "URLService", function ($log, ModalService, URLService) { var logger = $log.getInstance("AuthenticationModalsService"); $log.logLevels["AuthenticationModalsService"] = $log.LEVEL.OFF; function showForgotPasswordModal() { logger.info('called showForgotPasswordModal'); ModalService.closeModals(true); ModalService.showModal({ templateUrl: "partials/index/forgotten-password-dialog.html", controller: "ForgotPasswordController", preClose: function (modal) { modal.element.modal('hide'); } }).then(function (modal) { logger.info('modal event with modal', modal); modal.element.modal(); modal.close.then(function (result) { logger.info('close event with result', result); if (!result) URLService.navigateBackToLastMainPage(); }); }).catch(function (error) { logger.warn("error happened:", error); }) } function showResetPasswordModal(userName, message) { logger.info('called showResetPasswordModal for userName', userName); ModalService.closeModals(true); ModalService.showModal({ templateUrl: "partials/index/reset-password-dialog.html", controller: "ResetPasswordController", inputs: {userName: userName, message: message}, preClose: function (modal) { modal.element.modal('hide'); } }).then(function (modal) { logger.info('modal event with modal', modal); modal.element.modal(); modal.close.then(function (result) { logger.info('showResetPasswordModal close event with result', result); if (!result) URLService.navigateBackToLastMainPage(); }); }) } function showLoginDialog() { logger.info('called showLoginDialog'); ModalService.closeModals(true); ModalService.showModal({ templateUrl: "partials/index/login-dialog.html", controller: "LoginController", preClose: function (modal) { modal.element.modal('hide'); } }).then(function (modal) { logger.info('modal event with modal', modal); modal.element.modal(); modal.close.then(function (result) { logger.info('showLoginDialog close event with result', result); if (!result) URLService.navigateBackToLastMainPage(); }); }) } function showResetPasswordFailedDialog() { logger.info('called showResetPasswordFailedDialog'); ModalService.closeModals(true); ModalService.showModal({ templateUrl: "partials/index/reset-password-failed-dialog.html", controller: "ResetPasswordFailedController", preClose: function (modal) { modal.element.modal('hide'); } }).then(function (modal) { logger.info('showResetPasswordFailedDialog modal event with modal', modal); modal.element.modal(); modal.close.then(function (result) { logger.info('showResetPasswordFailedDialog close event with result', result); if (!result) URLService.navigateBackToLastMainPage(); }); }) } function showMailingPreferencesDialog(memberId) { logger.info('called showMailingPreferencesDialog'); ModalService.closeModals(true); ModalService.showModal({ templateUrl: "partials/index/mailing-preferences-dialog.html", controller: "MailingPreferencesController", inputs: {memberId: memberId}, preClose: function (modal) { modal.element.modal('hide'); } }).then(function (modal) { logger.info('showMailingPreferencesDialog modal event with modal', modal); modal.element.modal(); modal.close.then(function (result) { logger.info('close event with result', result); if (!result) URLService.navigateBackToLastMainPage(); }); }) } return { showResetPasswordModal: showResetPasswordModal, showResetPasswordFailedDialog: showResetPasswordFailedDialog, showForgotPasswordModal: showForgotPasswordModal, showLoginDialog: showLoginDialog, showMailingPreferencesDialog: showMailingPreferencesDialog } }]); /* concatenated from client/src/app/js/awsServices.js */ angular.module('ekwgApp') .factory('AWSConfig', ["$http", "HTTPResponseService", function ($http, HTTPResponseService) { function getConfig() { return $http.get('/aws/config').then(HTTPResponseService.returnResponse); } function awsPolicy(fileType, objectKey) { return $http.get('/aws/s3Policy?mimeType=' + fileType + '&objectKey=' + objectKey).then(HTTPResponseService.returnResponse); } return { getConfig: getConfig, awsPolicy: awsPolicy } }]) .factory('EKWGFileUpload', ["$log", "AWSConfig", "NumberUtils", "Upload", function ($log, AWSConfig, NumberUtils, Upload) { $log.logLevels['EKWGFileUpload'] = $log.LEVEL.OFF; var logger = $log.getInstance('EKWGFileUpload'); var awsConfig; AWSConfig.getConfig().then(function (config) { awsConfig = config; }); function onFileSelect(file, notify, objectKey) { logger.debug(file, objectKey); function generateFileNameData() { return { originalFileName: file.name, awsFileName: NumberUtils.generateUid() + '.' + _.last(file.name.split('.')) }; } var fileNameData = generateFileNameData(), fileUpload = file; fileUpload.progress = parseInt(0); logger.debug('uploading fileNameData', fileNameData); return AWSConfig.awsPolicy(file.type, objectKey) .then(function (response) { var s3Params = response; var url = 'https://' + awsConfig.bucket + '.s3.amazonaws.com/'; return Upload.upload({ url: url, method: 'POST', data: { 'key': objectKey + '/' + fileNameData.awsFileName, 'acl': 'public-read', 'Content-Type': file.type, 'AWSAccessKeyId': s3Params.AWSAccessKeyId, 'success_action_status': '201', 'Policy': s3Params.s3Policy, 'Signature': s3Params.s3Signature }, file: file }).then(function (response) { fileUpload.progress = parseInt(100); if (response.status === 201) { var data = xml2json.parser(response.data), parsedData; parsedData = { location: data.postresponse.location, bucket: data.postresponse.bucket, key: data.postresponse.key, etag: data.postresponse.etag }; logger.debug('parsedData', parsedData); return fileNameData; } else { notify.error('Upload Failed for file ' + fileNameData); } }, notify.error, function (evt) { fileUpload.progress = parseInt(100.0 * evt.loaded / evt.total); }); }); } return {onFileSelect: onFileSelect}; }]); /* concatenated from client/src/app/js/batchGeoServices.js */ angular.module('ekwgApp') .factory('BatchGeoExportService', ["StringUtils", "DateUtils", "$filter", function(StringUtils, DateUtils, $filter) { function exportWalksFileName() { return 'batch-geo-walks-export-' + DateUtils.asMoment().format('DD-MMMM-YYYY-HH-mm') + '.csv' } function exportableWalks(walks) { return _(walks).sortBy('walkDate'); } function exportWalks(walks) { return _.chain(walks) .filter(filterWalk) .sortBy('walkDate') .last(250) .map(walkToCsvRecord) .value(); } function filterWalk(walk) { return _.has(walk, 'briefDescriptionAndStartPoint') && (_.has(walk, 'gridReference') || _.has(walk, 'postcode')); } function exportColumnHeadings() { return [ "Walk Date", "Start Time", "Postcode", "Contact Name/Email", "Distance", "Description", "Longer Description", "Grid Ref" ]; } function walkToCsvRecord(walk) { return { "walkDate": walkDate(walk), "startTime": walkStartTime(walk), "postcode": walkPostcode(walk), "displayName": contactDisplayName(walk), "distance": walkDistanceMiles(walk), "description": walkTitle(walk), "longerDescription": walkDescription(walk), "gridRef": walkGridReference(walk) }; } function walkTitle(walk) { var walkDescription = []; if (walk.includeWalkDescriptionPrefix) walkDescription.push(walk.walkDescriptionPrefix); if (walk.briefDescriptionAndStartPoint) walkDescription.push(walk.briefDescriptionAndStartPoint); return _.chain(walkDescription).map(replaceSpecialCharacters).value().join('. '); } function walkDescription(walk) { return replaceSpecialCharacters(walk.longerDescription); } function asString(value) { return value ? value : ''; } function contactDisplayName(walk) { return walk.displayName ? replaceSpecialCharacters(_.first(walk.displayName.split(' '))) : ''; } function replaceSpecialCharacters(value) { return value ? StringUtils.stripLineBreaks(value .replace("’", "'") .replace("é", "e") .replace("’", "'") .replace('…', '…') .replace('–', '–') .replace('’', '’') .replace('“', '“')) : ''; } function walkDistanceMiles(walk) { return walk.distance ? String(parseFloat(walk.distance).toFixed(1)) : ''; } function walkStartTime(walk) { return walk.startTime ? DateUtils.asString(walk.startTime, 'HH mm', 'HH:mm') : ''; } function walkGridReference(walk) { return walk.gridReference ? walk.gridReference : ''; } function walkPostcode(walk) { return walk.postcode ? walk.postcode : ''; } function walkDate(walk) { return $filter('displayDate')(walk.walkDate); } return { exportWalksFileName: exportWalksFileName, exportWalks: exportWalks, exportableWalks: exportableWalks, exportColumnHeadings: exportColumnHeadings } }]); /* concatenated from client/src/app/js/bulkUploadServices.js */ angular.module('ekwgApp') .factory('MemberBulkUploadService', ["$log", "$q", "$filter", "MemberService", "MemberUpdateAuditService", "MemberBulkLoadAuditService", "ErrorMessageService", "EmailSubscriptionService", "DateUtils", "DbUtils", "MemberNamingService", function ($log, $q, $filter, MemberService, MemberUpdateAuditService, MemberBulkLoadAuditService, ErrorMessageService, EmailSubscriptionService, DateUtils, DbUtils, MemberNamingService) { var logger = $log.getInstance('MemberBulkUploadService'); var noLogger = $log.getInstance('NoLogger'); $log.logLevels['MemberBulkUploadService'] = $log.LEVEL.OFF; $log.logLevels['NoLogger'] = $log.LEVEL.OFF; var RESET_PASSWORD = 'changeme'; function processMembershipRecords(file, memberBulkLoadServerResponse, members, notify) { notify.setBusy(); var today = DateUtils.momentNowNoTime().valueOf(); var promises = []; var memberBulkLoadResponse = memberBulkLoadServerResponse.data; logger.debug('received', memberBulkLoadResponse); return DbUtils.auditedSaveOrUpdate(new MemberBulkLoadAuditService(memberBulkLoadResponse)) .then(function (auditResponse) { var uploadSessionId = auditResponse.$id(); return processBulkLoadResponses(promises, uploadSessionId); }); function updateGroupMembersPreBulkLoadProcessing(promises) { if (memberBulkLoadResponse.members && memberBulkLoadResponse.members.length > 1) { notify.progress('Processing ' + members.length + ' members ready for bulk load'); _.each(members, function (member) { if (member.receivedInLastBulkLoad) { member.receivedInLastBulkLoad = false; promises.push(DbUtils.auditedSaveOrUpdate(member, auditUpdateCallback(member), auditErrorCallback(member))); } }); return $q.all(promises).then(function () { notify.progress('Marked ' + promises.length + ' out of ' + members.length + ' in preparation for update'); return promises; }); } else { return $q.when(promises); } } function processBulkLoadResponses(promises, uploadSessionId) { return updateGroupMembersPreBulkLoadProcessing(promises).then(function (updatedPromises) { _.each(memberBulkLoadResponse.members, function (ramblersMember, recordIndex) { createOrUpdateMember(uploadSessionId, recordIndex, ramblersMember, updatedPromises); }); return $q.all(updatedPromises).then(function () { logger.debug('performed total of', updatedPromises.length, 'audit or member updates'); return updatedPromises; }); }); } function auditUpdateCallback(member) { return function (response) { logger.debug('auditUpdateCallback for member:', member, 'response', response); } } function auditErrorCallback(member, audit) { return function (response) { logger.warn('member save error for member:', member, 'response:', response); if (audit) { audit.auditErrorMessage = response; } } } function saveAndAuditMemberUpdate(promises, uploadSessionId, rowNumber, memberAction, changes, auditMessage, member) { var audit = new MemberUpdateAuditService({ uploadSessionId: uploadSessionId, updateTime: DateUtils.nowAsValue(), memberAction: memberAction, rowNumber: rowNumber, changes: changes, auditMessage: auditMessage }); var qualifier = 'for membership ' + member.membershipNumber; member.receivedInLastBulkLoad = true; member.lastBulkLoadDate = DateUtils.momentNow().valueOf(); return DbUtils.auditedSaveOrUpdate(member, auditUpdateCallback(member), auditErrorCallback(member, audit)) .then(function (savedMember) { if (savedMember) { audit.memberId = savedMember.$id(); notify.success({title: 'Bulk member load ' + qualifier + ' was successful', message: auditMessage}) } else { audit.member = member; audit.memberAction = 'error'; logger.warn('member was not saved, so saving it to audit:', audit); notify.warning({title: 'Bulk member load ' + qualifier + ' failed', message: auditMessage}) } logger.debug('saveAndAuditMemberUpdate:', audit); promises.push(audit.$save()); return promises; }); } function convertMembershipExpiryDate(ramblersMember) { var dataValue = ramblersMember.membershipExpiryDate ? DateUtils.asValueNoTime(ramblersMember.membershipExpiryDate, 'DD/MM/YYYY') : ramblersMember.membershipExpiryDate; logger.debug('ramblersMember', ramblersMember, 'membershipExpiryDate', ramblersMember.membershipExpiryDate, '->', DateUtils.displayDate(dataValue)); return dataValue; } function createOrUpdateMember(uploadSessionId, recordIndex, ramblersMember, promises) { var memberAction; ramblersMember.membershipExpiryDate = convertMembershipExpiryDate(ramblersMember); ramblersMember.groupMember = !ramblersMember.membershipExpiryDate || ramblersMember.membershipExpiryDate >= today; var member = _.find(members, function (member) { var existingUserName = MemberNamingService.createUserName(ramblersMember); var match = member.membershipNumber && member.membershipNumber.toString() === ramblersMember.membershipNumber; if (!match && member.userName) { match = member.userName === existingUserName; } noLogger.debug('match', !!(match), 'ramblersMember.membershipNumber', ramblersMember.membershipNumber, 'ramblersMember.userName', existingUserName, 'member.membershipNumber', member.membershipNumber, 'member.userName', member.userName); return match; }); if (member) { EmailSubscriptionService.resetUpdateStatusForMember(member); } else { memberAction = 'created'; member = new MemberService(); member.userName = MemberNamingService.createUniqueUserName(ramblersMember, members); member.displayName = MemberNamingService.createUniqueDisplayName(ramblersMember, members); member.password = RESET_PASSWORD; member.expiredPassword = true; EmailSubscriptionService.defaultMailchimpSettings(member, true); logger.debug('new member created:', member); } var updateAudit = {auditMessages: [], fieldsChanged: 0, fieldsSkipped: 0}; _.each([ {fieldName: 'membershipExpiryDate', writeDataIf: 'changed', type: 'date'}, {fieldName: 'membershipNumber', writeDataIf: 'changed', type: 'string'}, {fieldName: 'mobileNumber', writeDataIf: 'empty', type: 'string'}, {fieldName: 'email', writeDataIf: 'empty', type: 'string'}, {fieldName: 'firstName', writeDataIf: 'empty', type: 'string'}, {fieldName: 'lastName', writeDataIf: 'empty', type: 'string'}, {fieldName: 'postcode', writeDataIf: 'empty', type: 'string'}, {fieldName: 'groupMember', writeDataIf: 'not-revoked', type: 'boolean'}], function (field) { changeAndAuditMemberField(updateAudit, member, ramblersMember, field) }); DbUtils.removeEmptyFieldsIn(member); logger.debug('saveAndAuditMemberUpdate -> member:', member, 'updateAudit:', updateAudit); return saveAndAuditMemberUpdate(promises, uploadSessionId, recordIndex + 1, memberAction || (updateAudit.fieldsChanged > 0 ? 'updated' : 'skipped'), updateAudit.fieldsChanged, updateAudit.auditMessages.join(', '), member); } function changeAndAuditMemberField(updateAudit, member, ramblersMember, field) { function auditValueForType(field, source) { var dataValue = source[field.fieldName]; switch (field.type) { case 'date': return ($filter('displayDate')(dataValue) || '(none)'); case 'boolean': return dataValue || false; default: return dataValue || '(none)'; } } var fieldName = field.fieldName; var performMemberUpdate = false; var auditQualifier = ' not overwritten with '; var auditMessage; var oldValue = auditValueForType(field, member); var newValue = auditValueForType(field, ramblersMember); if (field.writeDataIf === 'changed') { performMemberUpdate = (oldValue !== newValue) && ramblersMember[fieldName]; } else if (field.writeDataIf === 'empty') { performMemberUpdate = !member[fieldName]; } else if (field.writeDataIf === 'not-revoked') { performMemberUpdate = newValue && (oldValue !== newValue) && !member.revoked; } else if (field.writeDataIf) { performMemberUpdate = newValue; } if (performMemberUpdate) { auditQualifier = ' updated to '; member[fieldName] = ramblersMember[fieldName]; updateAudit.fieldsChanged++; } if (oldValue !== newValue) { if (!performMemberUpdate) updateAudit.fieldsSkipped++; auditMessage = fieldName + ': ' + oldValue + auditQualifier + newValue; } if ((performMemberUpdate || (oldValue !== newValue)) && auditMessage) { updateAudit.auditMessages.push(auditMessage); } } } return { processMembershipRecords: processMembershipRecords, } }]); /* concatenated from client/src/app/js/clipboardService.js */ angular.module('ekwgApp') .factory('ClipboardService', ["$compile", "$rootScope", "$document", "$log", function ($compile, $rootScope, $document, $log) { return { copyToClipboard: function (element) { var logger = $log.getInstance("ClipboardService"); $log.logLevels['ClipboardService'] = $log.LEVEL.OFF; var copyElement = angular.element('<span id="clipboard-service-copy-id">' + element + '</span>'); var body = $document.find('body').eq(0); body.append($compile(copyElement)($rootScope)); var ClipboardServiceElement = angular.element(document.getElementById('clipboard-service-copy-id')); logger.debug(ClipboardServiceElement); var range = document.createRange(); range.selectNode(ClipboardServiceElement[0]); window.getSelection().removeAllRanges(); window.getSelection().addRange(range); var successful = document.execCommand('copy'); var msg = successful ? 'successful' : 'unsuccessful'; logger.debug('Copying text command was ' + msg); window.getSelection().removeAllRanges(); copyElement.remove(); } } }]); /* concatenated from client/src/app/js/comitteeNotifications.js */ angular.module('ekwgApp') .controller('CommitteeNotificationsController', ["$window", "$log", "$sce", "$timeout", "$templateRequest", "$compile", "$q", "$rootScope", "$scope", "$filter", "$routeParams", "$location", "URLService", "DateUtils", "NumberUtils", "LoggedInMemberService", "MemberService", "ContentMetaDataService", "CommitteeFileService", "MailchimpSegmentService", "MailchimpCampaignService", "MAILCHIMP_APP_CONSTANTS", "MailchimpConfig", "Notifier", "CommitteeReferenceData", "CommitteeQueryService", "committeeFile", "close", function ($window, $log, $sce, $timeout, $templateRequest, $compile, $q, $rootScope, $scope, $filter, $routeParams, $location, URLService, DateUtils, NumberUtils, LoggedInMemberService, MemberService, ContentMetaDataService, CommitteeFileService, MailchimpSegmentService, MailchimpCampaignService, MAILCHIMP_APP_CONSTANTS, MailchimpConfig, Notifier, CommitteeReferenceData, CommitteeQueryService, committeeFile, close) { var logger = $log.getInstance('CommitteeNotificationsController'); $log.logLevels['CommitteeNotificationsController'] = $log.LEVEL.OFF; $scope.notify = {}; var notify = Notifier($scope.notify); notify.setBusy(); $scope.members = []; $scope.committeeFile = committeeFile; $scope.roles = {signoff: CommitteeReferenceData.contactUsRolesAsArray(), replyTo: []}; $scope.committeeFileBaseUrl = ContentMetaDataService.baseUrl('committeeFiles'); function loggedOnRole() { var memberId = LoggedInMemberService.loggedInMember().memberId; var loggedOnRoleData = _(CommitteeReferenceData.contactUsRolesAsArray()).find(function (role) { return role.memberId === memberId }); logger.debug('loggedOnRole for', memberId, '->', loggedOnRoleData); return loggedOnRoleData || {}; } $scope.fromDateCalendar = { open: function ($event) { $event.preventDefault(); $event.stopPropagation(); $scope.fromDateCalendar.opened = true; } }; $scope.toDateCalendar = { open: function ($event) { $event.preventDefault(); $event.stopPropagation(); $scope.toDateCalendar.opened = true; } }; $scope.populateGroupEvents = function () { notify.setBusy(); populateGroupEvents().then(function () { notify.clearBusy(); return true; }) }; function populateGroupEvents() { return CommitteeQueryService.groupEvents($scope.userEdits.groupEvents) .then(function (events) { $scope.userEdits.groupEvents.events = events; logger.debug('groupEvents', events); return events; }); } $scope.changeGroupEventSelection = function (groupEvent) { groupEvent.selected = !groupEvent.selected; }; $scope.notification = { editable: { text: '', signoffText: 'If you have any questions about the above, please don\'t hesitate to contact me.\n\nBest regards,', }, destinationType: 'committee', includeSignoffText: true, addresseeType: 'Hi *|FNAME|*,', addingNewFile: false, recipients: [], groupEvents: function () { return _.filter($scope.userEdits.groupEvents.events, function (groupEvent) { logger.debug('notification.groupEvents ->', groupEvent); return groupEvent.selected; }); }, signoffAs: { include: true, value: loggedOnRole().type || 'secretary' }, includeDownloadInformation: $scope.committeeFile, title: 'Committee Notification', text: function () { return $filter('lineFeedsToBreaks')($scope.notification.editable.text); }, signoffText: function () { return $filter('lineFeedsToBreaks')($scope.notification.editable.signoffText); } }; if ($scope.committeeFile) { $scope.notification.title = $scope.committeeFile.fileType; $scope.notification.editable.text = 'This is just a quick note to let you know in case you are interested, that I\'ve uploaded a new file to the EKWG website. The file information is as follows:'; } logger.debug('initialised on open: committeeFile', $scope.committeeFile, ', roles', $scope.roles); logger.debug('initialised on open: notification ->', $scope.notification); $scope.userEdits = { sendInProgress: false, cancelled: false, groupEvents: { events: [], fromDate: DateUtils.momentNowNoTime().valueOf(), toDate: DateUtils.momentNowNoTime().add(2, 'weeks').valueOf(), includeContact: true, includeDescription: true, includeLocation: true, includeWalks: true, includeSocialEvents: true, includeCommitteeEvents: true }, allGeneralSubscribedList: function () { return _.chain($scope.members) .filter(MemberService.filterFor.GENERAL_MEMBERS_SUBSCRIBED) .map(toSelectGeneralMember).value(); }, allWalksSubscribedList: function () { return _.chain($scope.members) .filter(MemberService.filterFor.WALKS_MEMBERS_SUBSCRIBED) .map(toSelectWalksMember).value(); }, allSocialSubscribedList: function () { return _.chain($scope.members) .filter(MemberService.filterFor.SOCIAL_MEMBERS_SUBSCRIBED) .map(toSelectSocialMember).value(); }, allCommitteeList: function () { return _.chain($scope.members) .filter(MemberService.filterFor.COMMITTEE_MEMBERS) .map(toSelectGeneralMember).value(); }, replyToRole: function () { return _($scope.roles.replyTo).find(function (role) { return role.type === $scope.socialEvent.notification.items.replyTo.value; }); }, notReady: function () { return $scope.members.length === 0 || $scope.userEdits.sendInProgress || ($scope.notification.recipients.length === 0 && $scope.notification.destinationType === 'custom'); } }; function toSelectGeneralMember(member) { var memberGrouping; var order; if (member.groupMember && member.mailchimpLists.general.subscribed) { memberGrouping = 'Subscribed to general emails'; order = 0; } else if (member.groupMember && !member.mailchimpLists.general.subscribed) { memberGrouping = 'Not subscribed to general emails'; order = 1; } else if (!member.groupMember) { memberGrouping = 'Not a group member'; order = 2; } else { memberGrouping = 'Unexpected state'; order = 3; } return { id: member.$id(), order: order, memberGrouping: memberGrouping, text: $filter('fullNameWithAlias')(member) }; } function toSelectWalksMember(member) { var memberGrouping; var order; if (member.groupMember && member.mailchimpLists.walks.subscribed) { memberGrouping = 'Subscribed to walks emails'; order = 0; } else if (member.groupMember && !member.mailchimpLists.walks.subscribed) { memberGrouping = 'Not subscribed to walks emails'; order = 1; } else if (!member.groupMember) { memberGrouping = 'Not a group member'; order = 2; } else { memberGrouping = 'Unexpected state'; order = 3; } return { id: member.$id(), order: order, memberGrouping: memberGrouping, text: $filter('fullNameWithAlias')(member) }; } function toSelectSocialMember(member) { var memberGrouping; var order; if (member.groupMember && member.mailchimpLists.socialEvents.subscribed) { memberGrouping = 'Subscribed to social emails'; order = 0; } else if (member.groupMember && !member.mailchimpLists.socialEvents.subscribed) { memberGrouping = 'Not subscribed to social emails'; order = 1; } else if (!member.groupMember) { memberGrouping = 'Not a group member'; order = 2; } else { memberGrouping = 'Unexpected state'; order = 3; } return { id: member.$id(), order: order, memberGrouping: memberGrouping, text: $filter('fullNameWithAlias')(member) }; } $scope.editAllEKWGRecipients = function () { $scope.notification.destinationType = 'custom'; $scope.notification.campaignId = campaignIdFor('general'); $scope.notification.list = 'general'; $scope.notification.recipients = $scope.userEdits.allGeneralSubscribedList(); $scope.campaignIdChanged(); }; $scope.editAllWalksRecipients = function () { $scope.notification.destinationType = 'custom'; $scope.notification.campaignId = campaignIdFor('walks'); $scope.notification.list = 'walks'; $scope.notification.recipients = $scope.userEdits.allWalksSubscribedList(); $scope.campaignIdChanged(); }; $scope.editAllSocialRecipients = function () { $scope.notification.destinationType = 'custom'; $scope.notification.campaignId = campaignIdFor('socialEvents'); $scope.notification.list = 'socialEvents'; $scope.notification.recipients = $scope.userEdits.allSocialSubscribedList(); $scope.campaignIdChanged(); }; $scope.editCommitteeRecipients = function () { $scope.notification.destinationType = 'custom'; $scope.notification.campaignId = campaignIdFor('committee'); $scope.notification.list = 'general'; $scope.notification.recipients = $scope.userEdits.allCommitteeList(); $scope.campaignIdChanged(); }; $scope.clearRecipientsForCampaignOfType = function (campaignType) { $scope.notification.customCampaignType = campaignType; $scope.notification.campaignId = campaignIdFor(campaignType); $scope.notification.list = 'general'; $scope.notification.recipients = []; $scope.campaignIdChanged(); }; $scope.fileUrl = function () { return $scope.committeeFile && $scope.committeeFile.fileNameData ? URLService.baseUrl() + $scope.committeeFileBaseUrl + '/' + $scope.committeeFile.fileNameData.awsFileName : ''; }; $scope.fileTitle = function () { return $scope.committeeFile ? DateUtils.asString($scope.committeeFile.eventDate, undefined, DateUtils.formats.displayDateTh) + ' - ' + $scope.committeeFile.fileNameData.title : ''; }; function campaignIdFor(campaignType) { switch (campaignType) { case 'committee': return $scope.config.mailchimp.campaigns.committee.campaignId; case 'general': return $scope.config.mailchimp.campaigns.newsletter.campaignId; case 'socialEvents': return $scope.config.mailchimp.campaigns.socialEvents.campaignId; case 'walks': return $scope.config.mailchimp.campaigns.walkNotification.campaignId; default: return $scope.config.mailchimp.campaigns.committee.campaignId; } } function campaignInfoForCampaign(campaignId) { return _.chain($scope.config.mailchimp.campaigns) .map(function (data, campaignType) { var campaignData = _.extend({campaignType: campaignType}, data); logger.debug('campaignData for', campaignType, '->', campaignData); return campaignData; }).find({campaignId: campaignId}) .value(); } $scope.campaignIdChanged = function () { var infoForCampaign = campaignInfoForCampaign($scope.notification.campaignId); logger.debug('for campaignId', $scope.notification.campaignId, 'infoForCampaign', infoForCampaign); if (infoForCampaign) { $scope.notification.title = infoForCampaign.name; } }; $scope.confirmSendNotification = function (dontSend) { $scope.userEdits.sendInProgress = true; var campaignName = $scope.notification.title; notify.setBusy(); return $q.when(templateFor('partials/committee/committee-notification.html')) .then(renderTemplateContent) .then(populateContentSections) .then(sendEmailCampaign) .then(notifyEmailSendComplete) .catch(handleNotificationError); function templateFor(template) { return $templateRequest($sce.getTrustedResourceUrl(template)) } function handleNotificationError(errorResponse) { $scope.userEdits.sendInProgress = false; notify.clearBusy(); notify.error({ title: 'Your notification could not be sent', message: (errorResponse.message || errorResponse) + (errorResponse.error ? ('. Error was: ' + JSON.stringify(errorResponse.error)) : '') }); } function renderTemplateContent(templateData) { var task = $q.defer(); var templateFunction = $compile(templateData); var templateElement = templateFunction($scope); $timeout(function () { $scope.$digest(); task.resolve(templateElement.html()); }); return task.promise; } function populateContentSections(notificationText) { logger.debug('populateContentSections -> notificationText', notificationText); return { sections: { notification_text: notificationText } }; } function sendEmailCampaign(contentSections) { notify.progress(dontSend ? ('Preparing to complete ' + campaignName + ' in Mailchimp') : ('Sending ' + campaignName)); return MailchimpConfig.getConfig() .then(function (config) { var replyToRole = $scope.notification.signoffAs.value || 'secretary'; logger.debug('replyToRole', replyToRole); var members; var list = $scope.notification.list; var otherOptions = { from_name: CommitteeReferenceData.contactUsField(replyToRole, 'fullName'), from_email: CommitteeReferenceData.contactUsField(replyToRole, 'email'), list_id: config.mailchimp.lists[list] }; logger.debug('Sending ' + campaignName, 'with otherOptions', otherOptions); var segmentId = config.mailchimp.segments[list].committeeSegmentId; var campaignId = $scope.notification.campaignId; switch ($scope.notification.destinationType) { case 'custom': members = $scope.notification.recipients; break; case 'committee': members = $scope.userEdits.allCommitteeList(); break; default: members = []; break; } logger.debug('sendCommitteeNotification:notification->', $scope.notification); if (members.length === 0) { logger.debug('about to replicateAndSendWithOptions to', list, 'list with campaignName', campaignName, 'campaign Id', campaignId, 'dontSend', dontSend); return MailchimpCampaignService.replicateAndSendWithOptions({ campaignId: campaignId, campaignName: campaignName, contentSections: contentSections, otherSegmentOptions: otherOptions, dontSend: dontSend }).then(openInMailchimpIf(dontSend)); } else { var segmentName = MailchimpSegmentService.formatSegmentName('Committee Notification Recipients'); return MailchimpSegmentService.saveSegment(list, {segmentId: segmentId}, members, segmentName, $scope.members) .then(function (segmentResponse) { logger.debug('segmentResponse following save segment of segmentName:', segmentName, '->', segmentResponse); logger.debug('about to replicateAndSendWithOptions to committee with campaignName', campaignName, 'campaign Id', campaignId, 'segmentId', segmentResponse.segment.id); return MailchimpCampaignService.replicateAndSendWithOptions({ campaignId: campaignId, campaignName: campaignName, contentSections: contentSections, segmentId: segmentResponse.segment.id, otherSegmentOptions: otherOptions, dontSend: dontSend }).then(openInMailchimpIf(dontSend)); }); } }) } function openInMailchimpIf(dontSend) { return function (replicateCampaignResponse) { logger.debug('openInMailchimpIf:replicateCampaignResponse', replicateCampaignResponse, 'dontSend', dontSend); if (dontSend) { return $window.open(MAILCHIMP_APP_CONSTANTS.apiServer + "/campaigns/wizard/neapolitan?id=" + replicateCampaignResponse.web_id, '_blank'); } else { return true; } } } function notifyEmailSendComplete() { if (!$scope.userEdits.cancelled) { notify.success('Sending of ' + campaignName + ' was successful.', false); $scope.userEdits.sendInProgress = false; $scope.cancelSendNotification(); } notify.clearBusy(); } }; $scope.completeInMailchimp = function () { notify.warning({ title: 'Complete in Mailchimp', message: 'You can close this dialog now as the message was presumably completed and sent in Mailchimp' }); $scope.confirmSendNotification(true); }; $scope.cancelSendNotification = function () { if ($scope.userEdits.sendInProgress) { $scope.userEdits.sendInProgress = false; $scope.userEdits.cancelled = true; notify.error({ title: 'Cancelling during send', message: "Because notification sending was already in progress when you cancelled, campaign may have already been sent - check in Mailchimp if in doubt." }); } else { logger.debug('calling cancelSendNotification'); close(); } }; var promises = [ MemberService.allLimitedFields(MemberService.filterFor.GROUP_MEMBERS).then(function (members) { $scope.members = members; logger.debug('refreshMembers -> populated ->', $scope.members.length, 'members'); $scope.selectableRecipients = _.chain(members) .map(toSelectGeneralMember) .sortBy(function (member) { return member.order + member.text }) .value(); logger.debug('refreshMembers -> populated ->', $scope.selectableRecipients.length, 'selectableRecipients'); }), MailchimpConfig.getConfig() .then(function (config) { $scope.config = config; logger.debug('retrieved config', $scope.config); $scope.clearRecipientsForCampaignOfType('committee'); }), MailchimpCampaignService.list({ limit: 1000, concise: true, status: 'save', title: 'Master' }).then(function (response) { $scope.campaigns = response.data; logger.debug('response.data', response.data); })]; if (!$scope.committeeFile) promises.push(populateGroupEvents()); $q.all(promises).then(function () { logger.debug('performed total of', promises.length); notify.clearBusy(); }); }] ); /* concatenated from client/src/app/js/committee.js */ angular.module('ekwgApp') .controller('CommitteeController', ["$rootScope", "$window", "$log", "$sce", "$timeout", "$templateRequest", "$compile", "$q", "$scope", "$filter", "$routeParams", "$location", "URLService", "DateUtils", "NumberUtils", "LoggedInMemberService", "MemberService", "ContentMetaDataService", "CommitteeFileService", "MailchimpSegmentService", "MailchimpCampaignService", "MAILCHIMP_APP_CONSTANTS", "MailchimpConfig", "Notifier", "EKWGFileUpload", "CommitteeQueryService", "CommitteeReferenceData", "ModalService", function ($rootScope, $window, $log, $sce, $timeout, $templateRequest, $compile, $q, $scope, $filter, $routeParams, $location, URLService, DateUtils, NumberUtils, LoggedInMemberService, MemberService, ContentMetaDataService, CommitteeFileService, MailchimpSegmentService, MailchimpCampaignService, MAILCHIMP_APP_CONSTANTS, MailchimpConfig, Notifier, EKWGFileUpload, CommitteeQueryService, CommitteeReferenceData, ModalService) { var logger = $log.getInstance('CommitteeController'); $log.logLevels['CommitteeController'] = $log.LEVEL.OFF; var notify = Notifier($scope); notify.setBusy(); $scope.emailingInProgress = false; $scope.committeeFileBaseUrl = ContentMetaDataService.baseUrl('committeeFiles'); $scope.destinationType = ''; $scope.members = []; $scope.committeeFiles = []; $scope.alertMessages = []; $scope.allowConfirmDelete = false; $scope.latestYearOpen = true; $scope.committeeReferenceData = CommitteeReferenceData; $scope.selected = { addingNewFile: false, committeeFiles: [] }; $rootScope.$on('CommitteeReferenceDataReady', function () { assignFileTypes(); }); function assignFileTypes() { $scope.fileTypes = CommitteeReferenceData.fileTypes; logger.debug('CommitteeReferenceDataReady -> fileTypes ->', $scope.fileTypes); } $scope.userEdits = { saveInProgress: false }; $scope.showAlertMessage = function () { return ($scope.alert.class === 'alert-danger') || $scope.emailingInProgress; }; $scope.latestYear = function () { return CommitteeQueryService.latestYear($scope.committeeFiles) }; $scope.committeeFilesForYear = function (year) { return CommitteeQueryService.committeeFilesForYear(year, $scope.committeeFiles) }; $scope.isActive = function (committeeFile) { return committeeFile === $scope.selected.committeeFile; }; $scope.eventDateCalendar = { open: function ($event) { $scope.eventDateCalendar.opened = true; } }; $scope.allowSend = function () { return LoggedInMemberService.allowFileAdmin(); }; $scope.allowAddCommitteeFile = function () { return $scope.fileTypes && LoggedInMemberService.allowFileAdmin(); }; $scope.allowEditCommitteeFile = function (committeeFile) { return $scope.allowAddCommitteeFile() && committeeFile && committeeFile.$id(); }; $scope.allowDeleteCommitteeFile = function (committeeFile) { return $scope.allowEditCommitteeFile(committeeFile); }; $scope.cancelFileChange = function () { $q.when($scope.hideCommitteeFileDialog()).then(refreshCommitteeFiles).then(notify.clearBusy); }; $scope.saveCommitteeFile = function () { $scope.userEdits.saveInProgress = true; $scope.selected.committeeFile.eventDate = DateUtils.asValueNoTime($scope.selected.committeeFile.eventDate); logger.debug('saveCommitteeFile ->', $scope.selected.committeeFile); return $scope.selected.committeeFile.$saveOrUpdate(notify.success, notify.success, notify.error, notify.error) .then($scope.hideCommitteeFileDialog) .then(refreshCommitteeFiles) .then(notify.clearBusy) .catch(handleError); function handleError(errorResponse) { $scope.userEdits.saveInProgress = false; notify.error({ title: 'Your changes could not be saved', message: (errorResponse && errorResponse.error ? ('. Error was: ' + JSON.stringify(errorResponse.error)) : '') }); notify.clearBusy(); } }; var defaultCommitteeFile = function () { return _.clone({ "createdDate": DateUtils.nowAsValue(), "fileType": $scope.fileTypes && $scope.fileTypes[0].description, "fileNameData": {} }) }; function removeDeleteOrAddOrInProgressFlags() { $scope.allowConfirmDelete = false; $scope.selected.addingNewFile = false; $scope.userEdits.saveInProgress = false; } $scope.deleteCommitteeFile = function () { $scope.allowConfirmDelete = true; }; $scope.cancelDeleteCommitteeFile = function () { removeDeleteOrAddOrInProgressFlags(); }; $scope.confirmDeleteCommitteeFile = function () { $scope.userEdits.saveInProgress = true; function showCommitteeFileDeleted() { return notify.success('File was deleted successfully'); } $scope.selected.committeeFile.$remove(showCommitteeFileDeleted, showCommitteeFileDeleted, notify.error, notify.error) .then($scope.hideCommitteeFileDialog) .then(refreshCommitteeFiles) .then(removeDeleteOrAddOrInProgressFlags) .then(notify.clearBusy); }; $scope.selectCommitteeFile = function (committeeFile, committeeFiles) { if (!$scope.selected.addingNewFile) { $scope.selected.committeeFile = committeeFile; $scope.selected.committeeFiles = committeeFiles; } }; $scope.editCommitteeFile = function () { removeDeleteOrAddOrInProgressFlags(); delete $scope.uploadedFile; $('#file-detail-dialog').modal('show'); }; $scope.openMailchimp = function () { $window.open(MAILCHIMP_APP_CONSTANTS.apiServer + "/campaigns", '_blank'); }; $scope.openSettings = function () { ModalService.showModal({ templateUrl: "partials/committee/notification-settings-dialog.html", controller: "CommitteeNotificationSettingsController", preClose: function (modal) { logger.debug('preClose event with modal', modal); modal.element.modal('hide'); }, }).then(function (modal) { logger.debug('modal event with modal', modal); modal.element.modal(); modal.close.then(function (result) { logger.debug('close event with result', result); }); }) }; $scope.sendNotification = function (committeeFile) { ModalService.showModal({ templateUrl: "partials/committee/send-notification-dialog.html", controller: "CommitteeNotificationsController", preClose: function (modal) { logger.debug('preClose event with modal', modal); modal.element.modal('hide'); }, inputs: { committeeFile: committeeFile } }).then(function (modal) { logger.debug('modal event with modal', modal); modal.element.modal(); modal.close.then(function (result) { logger.debug('close event with result', result); }); }) }; $scope.cancelSendNotification = function () { $('#send-notification-dialog').modal('hide'); $scope.resubmit = false; }; $scope.addCommitteeFile = function ($event) { $event.stopPropagation(); $scope.selected.addingNewFile = true; var committeeFile = new CommitteeFileService(defaultCommitteeFile()); $scope.selected.committeeFiles.push(committeeFile); $scope.selected.committeeFile = committeeFile; logger.debug('addCommitteeFile:', committeeFile, 'of', $scope.selected.committeeFiles.length, 'files'); $scope.editCommitteeFile(); }; $scope.hideCommitteeFileDialog = function () { removeDeleteOrAddOrInProgressFlags(); $('#file-detail-dialog').modal('hide'); }; $scope.attachFile = function (file) { $scope.oldTitle = $scope.selected.committeeFile.fileNameData ? $scope.selected.committeeFile.fileNameData.title : file.name; logger.debug('then:attachFile:oldTitle', $scope.oldTitle); $('#hidden-input').click(); }; $scope.onFileSelect = function (file) { if (file) { $scope.userEdits.saveInProgress = true; logger.debug('onFileSelect:file:about to upload ->', file); $scope.uploadedFile = file; EKWGFileUpload.onFileSelect(file, notify, 'committeeFiles') .then(function (fileNameData) { logger.debug('onFileSelect:file:upload complete -> fileNameData', fileNameData); $scope.selected.committeeFile.fileNameData = fileNameData; $scope.selected.committeeFile.fileNameData.title = $scope.oldTitle || file.name; $scope.userEdits.saveInProgress = false; }); } }; $scope.attachmentTitle = function () { return ($scope.selected.committeeFile && _.isEmpty($scope.selected.committeeFile.fileNameData) ? 'Attach' : 'Replace') + ' File'; }; $scope.fileUrl = function (committeeFile) { return committeeFile && committeeFile.fileNameData ? URLService.baseUrl() + $scope.committeeFileBaseUrl + '/' + committeeFile.fileNameData.awsFileName : ''; }; $scope.fileTitle = function (committeeFile) { return committeeFile ? DateUtils.asString(committeeFile.eventDate, undefined, DateUtils.formats.displayDateTh) + ' - ' + committeeFile.fileNameData.title : ''; }; $scope.iconFile = function (committeeFile) { if (!committeeFile.fileNameData) return undefined; function fileExtensionIs(fileName, extensions) { return _.contains(extensions, fileExtension(fileName)); } function fileExtension(fileName) { return fileName ? _.last(fileName.split('.')).toLowerCase() : ''; } if (fileExtensionIs(committeeFile.fileNameData.awsFileName, ['doc', 'docx', 'jpg', 'pdf', 'ppt', 'png', 'txt', 'xls', 'xlsx'])) { return 'icon-' + fileExtension(committeeFile.fileNameData.awsFileName).substring(0, 3) + '.jpg'; } else { return 'icon-default.jpg'; } }; $scope.$on('memberLoginComplete', function () { refreshAll(); }); $scope.$on('memberLogoutComplete', function () { refreshAll(); }); function refreshMembers() { function assignMembersToScope(members) { $scope.members = members; return $scope.members; } if (LoggedInMemberService.allowFileAdmin()) { return MemberService.all() .then(assignMembersToScope); } } function refreshCommitteeFiles() { CommitteeQueryService.committeeFiles(notify).then(function (files) { logger.debug('committeeFiles', files); if (URLService.hasRouteParameter('committeeFileId')) { $scope.committeeFiles = _.filter(files, function (file) { return file.$id() === $routeParams.committeeFileId; }); } else { $scope.committeeFiles = files; } $scope.committeeFileYears = CommitteeQueryService.committeeFileYears($scope.committeeFiles); }); } function refreshAll() { refreshCommitteeFiles(); refreshMembers(); } assignFileTypes(); refreshAll(); }]); /* concatenated from client/src/app/js/committeeData.js */ angular.module('ekwgApp') .factory('CommitteeConfig', ["Config", function (Config) { function getConfig() { return Config.getConfig('committee', { committee: { contactUs: { chairman: {description: 'Chairman', fullName: 'Claire Mansfield', email: 'chairman@ekwg.co.uk'}, secretary: {description: 'Secretary', fullName: 'Kerry O\'Grady', email: 'secretary@ekwg.co.uk'}, treasurer: {description: 'Treasurer', fullName: 'Marianne Christensen', email: 'treasurer@ekwg.co.uk'}, membership: {description: 'Membership', fullName: 'Desiree Nel', email: 'membership@ekwg.co.uk'}, social: {description: 'Social Co-ordinator', fullName: 'Suzanne Graham Beer', email: 'social@ekwg.co.uk'}, walks: {description: 'Walks Co-ordinator', fullName: 'Stuart Maisner', email: 'walks@ekwg.co.uk'}, support: {description: 'Technical Support', fullName: 'Nick Barrett', email: 'nick.barrett@ekwg.co.uk'} }, fileTypes: [ {description: "AGM Agenda", public: true}, {description: "AGM Minutes", public: true}, {description: "Committee Meeting Agenda"}, {description: "Committee Meeting Minutes"}, {description: "Financial Statements", public: true} ] } }) } function saveConfig(config, saveCallback, errorSaveCallback) { return Config.saveConfig('committee', config, saveCallback, errorSaveCallback); } return { getConfig: getConfig, saveConfig: saveConfig } }]) .factory('CommitteeFileService', ["$mongolabResourceHttp", function ($mongolabResourceHttp) { return $mongolabResourceHttp('committeeFiles'); }]) .factory('CommitteeReferenceData', ["$rootScope", function ($rootScope) { var refData = { contactUsRoles: function () { var keys = _.keys(refData.contactUs); if (keys.length > 0) { return keys; } }, contactUsField: function (role, field) { return refData.contactUs && refData.contactUs[role][field] }, fileTypesField: function (type, field) { return refData.fileTypes && refData.fileTypes[type][field] }, toFileType: function (fileTypeDescription, fileTypes) { return _.find(fileTypes, {description: fileTypeDescription}); }, contactUsRolesAsArray: function () { return _.map(refData.contactUs, function (data, type) { return { type: type, fullName: data.fullName, memberId: data.memberId, description: data.description + ' (' + data.fullName + ')', email: data.email }; }); } }; $rootScope.$on('CommitteeReferenceDataReady', function () { refData.ready = true; }); return refData; }]) .factory('CommitteeQueryService', ["$q", "$log", "$filter", "$routeParams", "URLService", "CommitteeFileService", "CommitteeReferenceData", "DateUtils", "LoggedInMemberService", "WalksService", "SocialEventsService", function ($q, $log, $filter, $routeParams, URLService, CommitteeFileService, CommitteeReferenceData, DateUtils, LoggedInMemberService, WalksService, SocialEventsService) { var logger = $log.getInstance('CommitteeQueryService'); $log.logLevels['CommitteeQueryService'] = $log.LEVEL.OFF; function groupEvents(groupEvents) { logger.debug('groupEvents', groupEvents); var fromDate = DateUtils.convertDateField(groupEvents.fromDate); var toDate = DateUtils.convertDateField(groupEvents.toDate); logger.debug('groupEvents:fromDate', $filter('displayDate')(fromDate), 'toDate', $filter('displayDate')(toDate)); var events = []; var promises = []; if (groupEvents.includeWalks) promises.push( WalksService.query({walkDate: {$gte: fromDate, $lte: toDate}}) .then(function (walks) { return _.map(walks, function (walk) { return events.push({ id: walk.$id(), selected: true, eventType: 'Walk', area: 'walks', type: 'walk', eventDate: walk.walkDate, eventTime: walk.startTime, distance: walk.distance, postcode: walk.postcode, title: walk.briefDescriptionAndStartPoint || 'Awaiting walk details', description: walk.longerDescription, contactName: walk.displayName || 'Awaiting walk leader', contactPhone: walk.contactPhone, contactEmail: walk.contactEmail }); }) })); if (groupEvents.includeCommitteeEvents) promises.push( CommitteeFileService.query({eventDate: {$gte: fromDate, $lte: toDate}}) .then(function (committeeFiles) { return _.map(committeeFiles, function (committeeFile) { return events.push({ id: committeeFile.$id(), selected: true, eventType: 'AGM & Committee', area: 'committee', type: 'committeeFile', eventDate: committeeFile.eventDate, postcode: committeeFile.postcode, description: committeeFile.fileType, title: committeeFile.fileNameData.title }); }) })); if (groupEvents.includeSocialEvents) promises.push( SocialEventsService.query({eventDate: {$gte: fromDate, $lte: toDate}}) .then(function (socialEvents) { return _.map(socialEvents, function (socialEvent) { return events.push({ id: socialEvent.$id(), selected: true, eventType: 'Social Event', area: 'social', type: 'socialEvent', eventDate: socialEvent.eventDate, eventTime: socialEvent.eventTimeStart, postcode: socialEvent.postcode, title: socialEvent.briefDescription, description: socialEvent.longerDescription, contactName: socialEvent.displayName, contactPhone: socialEvent.contactPhone, contactEmail: socialEvent.contactEmail }); }) })); return $q.all(promises).then(function () { logger.debug('performed total of', promises.length, 'events of length', events.length); return _.chain(events) .sortBy('eventDate') .value(); }); } function committeeFilesLatestFirst(committeeFiles) { return _.chain(committeeFiles) .sortBy('eventDate') .reverse() .value(); } function latestYear(committeeFiles) { return _.first( _.chain(committeeFilesLatestFirst(committeeFiles)) .pluck('eventDate') .map(function (eventDate) { return parseInt(DateUtils.asString(eventDate, undefined, 'YYYY')); }) .value()); } function committeeFilesForYear(year, committeeFiles) { var latestYearValue = latestYear(committeeFiles); return _.filter(committeeFilesLatestFirst(committeeFiles), function (committeeFile) { var fileYear = extractYear(committeeFile); return (fileYear === year) || (!fileYear && (latestYearValue === year)); }); } function extractYear(committeeFile) { return parseInt(DateUtils.asString(committeeFile.eventDate, undefined, 'YYYY')); } function committeeFileYears(committeeFiles) { var latestYearValue = latestYear(committeeFiles); function addLatestYearFlag(committeeFileYear) { return {year: committeeFileYear, latestYear: latestYearValue === committeeFileYear}; } var years = _.chain(committeeFiles) .map(extractYear) .unique() .sort() .map(addLatestYearFlag) .reverse() .value(); logger.debug('committeeFileYears', years); return years.length === 0 ? [{year: latestYear(committeeFiles), latestYear: true}] : years; } function committeeFiles(notify) { notify.progress('Refreshing Committee files...'); function queryCommitteeFiles() { if (URLService.hasRouteParameter('committeeFileId')) { return CommitteeFileService.getById($routeParams.committeeFileId) .then(function (committeeFile) { if (!committeeFile) notify.error('Committee file could not be found. Try opening again from the link in the notification email'); return [committeeFile]; }); } else { return CommitteeFileService.all().then(function (files) { return filterCommitteeFiles(files); }); } } return queryCommitteeFiles() .then(function (committeeFiles) { notify.progress('Found ' + committeeFiles.length + ' committee file(s)'); notify.setReady(); return _.chain(committeeFiles) .sortBy('fileDate') .reverse() .sortBy('createdDate') .value(); }, notify.error); } function filterCommitteeFiles(files) { logger.debug('filterCommitteeFiles files ->', files); var filteredFiles = _.filter(files, function (file) { return CommitteeReferenceData.fileTypes && CommitteeReferenceData.toFileType(file.fileType, CommitteeReferenceData.fileTypes).public || LoggedInMemberService.allowCommittee() || LoggedInMemberService.allowFileAdmin(); }); logger.debug('filterCommitteeFiles in ->', files && files.length, 'out ->', filteredFiles.length, 'CommitteeReferenceData.fileTypes', CommitteeReferenceData.fileTypes); return filteredFiles } return { groupEvents: groupEvents, committeeFiles: committeeFiles, latestYear: latestYear, committeeFileYears: committeeFileYears, committeeFilesForYear: committeeFilesForYear } }] ); /* concatenated from client/src/app/js/committeeNotificationSettingsController.js */ angular.module('ekwgApp') .controller('CommitteeNotificationSettingsController', ["$window", "$log", "$sce", "$timeout", "$templateRequest", "$compile", "$q", "$rootScope", "$scope", "$filter", "$routeParams", "$location", "URLService", "DateUtils", "NumberUtils", "LoggedInMemberService", "MemberService", "ContentMetaDataService", "CommitteeFileService", "MailchimpSegmentService", "MailchimpCampaignService", "MAILCHIMP_APP_CONSTANTS", "MailchimpConfig", "Notifier", "close", function ($window, $log, $sce, $timeout, $templateRequest, $compile, $q, $rootScope, $scope, $filter, $routeParams, $location, URLService, DateUtils, NumberUtils, LoggedInMemberService, MemberService, ContentMetaDataService, CommitteeFileService, MailchimpSegmentService, MailchimpCampaignService, MAILCHIMP_APP_CONSTANTS, MailchimpConfig, Notifier, close) { var logger = $log.getInstance('CommitteeNotificationSettingsController'); $log.logLevels['CommitteeNotificationSettingsController'] = $log.LEVEL.OFF; $scope.notify = {}; $scope.campaigns = []; var notify = Notifier($scope.notify); var campaignSearchTerm = 'Master'; notify.setBusy(); notify.progress({ title: 'Mailchimp Campaigns', message: 'Getting campaign information matching "' + campaignSearchTerm + '"' }); $scope.notReady = function () { return $scope.campaigns.length === 0; }; MailchimpConfig.getConfig() .then(function (config) { $scope.config = config; logger.debug('retrieved config', $scope.config); }); MailchimpCampaignService.list({ limit: 1000, concise: true, status: 'save', title: campaignSearchTerm }).then(function (response) { $scope.campaigns = response.data; logger.debug('response.data', response.data); notify.success({ title: 'Mailchimp Campaigns', message: 'Found ' + $scope.campaigns.length + ' draft campaigns matching "' + campaignSearchTerm + '"' }); notify.clearBusy(); }); $scope.editCampaign = function (campaignId) { if (!campaignId) { notify.error({ title: 'Edit Mailchimp Campaign', message: 'Please select a campaign from the drop-down before choosing edit' }); } else { notify.hide(); var webId = _.find($scope.campaigns, function (campaign) { return campaign.id === campaignId; }).web_id; logger.debug('editCampaign:campaignId', campaignId, 'web_id', webId); $window.open(MAILCHIMP_APP_CONSTANTS.apiServer + "/campaigns/edit?id=" + webId, '_blank'); } }; $scope.save = function () { logger.debug('saving config', $scope.config); MailchimpConfig.saveConfig($scope.config).then(close).catch(notify.error); }; $scope.cancel = function () { close(); }; }] ); /* concatenated from client/src/app/js/contentMetaServices.js */ angular.module('ekwgApp') .factory('ContentMetaDataService', ["ContentMetaData", "$q", function (ContentMetaData, $q) { var baseUrl = function (metaDataPathSegment) { return '/aws/s3/' + metaDataPathSegment; }; var createNewMetaData = function (withDefaults) { if (withDefaults) { return {image: '/(select file)', text: '(Enter title here)'}; } else { return {}; } }; var getMetaData = function (contentMetaDataType) { var task = $q.defer(); ContentMetaData.query({contentMetaDataType: contentMetaDataType}, {limit: 1}) .then(function (results) { if (results && results.length > 0) { task.resolve(results[0]); } else { task.resolve(new ContentMetaData({ contentMetaDataType: contentMetaDataType, baseUrl: baseUrl(contentMetaDataType), files: [createNewMetaData(true)] })); } }, function (response) { task.reject('Query of contentMetaDataType for ' + contentMetaDataType + ' failed: ' + response); }); return task.promise; }; var saveMetaData = function (metaData, saveCallback, errorSaveCallback) { return metaData.$saveOrUpdate(saveCallback, saveCallback, errorSaveCallback, errorSaveCallback); }; return { baseUrl: baseUrl, getMetaData: getMetaData, createNewMetaData: createNewMetaData, saveMetaData: saveMetaData } }]) .factory('ContentMetaData', ["$mongolabResourceHttp", function ($mongolabResourceHttp) { return $mongolabResourceHttp('contentMetaData'); }]) .factory('ContentTextService', ["$mongolabResourceHttp", function ($mongolabResourceHttp) { return $mongolabResourceHttp('contentText'); }]) .factory('ContentText', ["ContentTextService", function (ContentTextService) { function forName(name) { return ContentTextService.all().then(function (contentDocuments) { return _.findWhere(contentDocuments, {name: name}) || new ContentTextService({name: name}); }); } return {forName: forName} }]); /* concatenated from client/src/app/js/directives.js */ angular.module('ekwgApp') .directive('contactUs', ["$log", "$compile", "URLService", "CommitteeReferenceData", function ($log, $compile, URLService, CommitteeReferenceData) { var logger = $log.getInstance('contactUs'); $log.logLevels['contactUs'] = $log.LEVEL.OFF; function email(role) { return CommitteeReferenceData.contactUsField(role, 'email'); } function description(role) { return CommitteeReferenceData.contactUsField(role, 'description'); } function fullName(role) { return CommitteeReferenceData.contactUsField(role, 'fullName'); } function createHref(scope, role) { return '<a href="mailto:' + email(role) + '">' + (scope.text || email(role)) + '</a>'; } function createListItem(scope, role) { return '<li ' + 'style="' + 'font-weight: normal;' + 'padding: 4px 0px 4px 21px;' + 'list-style: none;' + 'background-image: url(' + URLService.baseUrl() + '/assets/images/ramblers/bull-green.png);' + 'background-position: 0px 9px;' + 'background-repeat: no-repeat no-repeat">' + fullName(role) + ' - ' + description(role) + ' - ' + '<a href="mailto:' + email(role) + '"' + 'style="' + 'background-color: transparent;' + 'color: rgb(120, 35, 39);' + 'text-decoration: none; ' + 'font-weight: bold; ' + 'background-position: initial; ' + 'background-repeat: initial;">' + (scope.text || email(role)) + '</a>' + '</li>'; } function expandRoles(scope) { var roles = scope.role ? scope.role.split(',') : CommitteeReferenceData.contactUsRoles(); logger.debug('role ->', scope.role, ' roles ->', roles); return _(roles).map(function (role) { if (scope.format === 'list') { return createListItem(scope, role); } else { return createHref(scope, role); } }).join('\n'); } function wrapInUL(scope) { if (scope.format === 'list') { return '<ul style="' + 'margin: 10px 0 0;' + 'padding: 0 0 10px 10px;' + 'font-weight: bold;' + 'background-image: url(' + URLService.baseUrl() + '/assets/images/ramblers/dot-darkgrey-hor.png);' + 'background-position: 0% 100%;' + 'background-repeat: repeat no-repeat;' + 'margin-bottom: 20px;"> ' + (scope.heading || '') + expandRoles(scope) + '</ul>'; } else { return expandRoles(scope); } } return { restrict: 'EA', replace: true, link: function (scope, element) { scope.$watch('name', function () { if (CommitteeReferenceData.ready) { var html = wrapInUL(scope); logger.debug('html before compile ->', html); element.html($compile(html)(scope)); } }); }, scope: { format: '@', text: '@', role: '@', heading: '@' } }; }]); /* concatenated from client/src/app/js/emailerService.js */ angular.module('ekwgApp') .factory('EmailSubscriptionService', ["$rootScope", "$log", "$http", "$q", "MemberService", "DateUtils", "MailchimpErrorParserService", function ($rootScope, $log, $http, $q, MemberService, DateUtils, MailchimpErrorParserService) { var logger = $log.getInstance('EmailSubscriptionService'); $log.logLevels['EmailSubscriptionService'] = $log.LEVEL.OFF; var resetAllBatchSubscriptions = function (members, subscribedState) { var deferredTask = $q.defer(); var savePromises = []; deferredTask.notify('Resetting Mailchimp subscriptions for ' + members.length + ' members'); _.each(members, function (member) { defaultMailchimpSettings(member, subscribedState); savePromises.push(member.$saveOrUpdate()); }); $q.all(savePromises).then(function () { deferredTask.notify('Reset of Mailchimp subscriptions completed. Next member save will resend all lists to Mailchimp'); MemberService.all().then(function (refreshedMembers) { deferredTask.resolve(refreshedMembers); }) }); }; function defaultMailchimpSettings(member, subscribedState) { member.mailchimpLists = { "walks": {"subscribed": subscribedState}, "socialEvents": {"subscribed": subscribedState}, "general": {"subscribed": subscribedState} } } function booleanToString(value) { return String(value || false); } function addMailchimpIdentifiersToRequest(member, listType, request) { var mailchimpIdentifiers = {email: {}}; mailchimpIdentifiers.email.email = member.email; if (member.mailchimpLists[listType].leid) { mailchimpIdentifiers.email.leid = member.mailchimpLists[listType].leid; } if (request) { return angular.extend(request, mailchimpIdentifiers); } else { return mailchimpIdentifiers.email; } } var createBatchSubscriptionForList = function (listType, members) { var deferredTask = $q.defer(); var progress = 'Sending ' + listType + ' member data to Mailchimp'; deferredTask.notify(progress); var batchedMembers = []; var subscriptionEntries = _.chain(members) .filter(function (member) { return includeMemberInSubscription(listType, member); }) .map(function (member) { batchedMembers.push(member); var request = { "merge_vars": { "FNAME": member.firstName, "LNAME": member.lastName, "MEMBER_NUM": member.membershipNumber, "MEMBER_EXP": DateUtils.displayDate(member.membershipExpiryDate), "USERNAME": member.userName, "PW_RESET": member.passwordResetId || '' } }; return addMailchimpIdentifiersToRequest(member, listType, request); }).value(); if (subscriptionEntries.length > 0) { var url = '/mailchimp/lists/' + listType + '/batchSubscribe'; logger.debug('sending', subscriptionEntries.length, listType, 'subscriptions to mailchimp', subscriptionEntries); $http({method: 'POST', url: url, data: subscriptionEntries}) .then(function (response) { var responseData = response.data; logger.debug('received response', responseData); var errorObject = MailchimpErrorParserService.extractError(responseData); if (errorObject.error) { var errorResponse = { message: 'Sending of ' + listType + ' list subscription to Mailchimp was not successful', error: errorObject.error }; deferredTask.reject(errorResponse); } else { var totalResponseCount = responseData.updates.concat(responseData.adds).concat(responseData.errors).length; deferredTask.notify('Send of ' + subscriptionEntries.length + ' ' + listType + ' members completed - processing ' + totalResponseCount + ' Mailchimp response(s)'); var savePromises = []; processValidResponses(listType, responseData.updates.concat(responseData.adds), batchedMembers, savePromises, deferredTask); processErrorResponses(listType, responseData.errors, batchedMembers, savePromises, deferredTask); $q.all(savePromises).then(function () { MemberService.all().then(function (refreshedMembers) { deferredTask.notify('Send of ' + subscriptionEntries.length + ' members to ' + listType + ' list completed with ' + responseData.add_count + ' member(s) added, ' + responseData.update_count + ' updated and ' + responseData.error_count + ' error(s)'); deferredTask.resolve(refreshedMembers); }) }); } }).catch(function (response) { var data = response.data; var errorMessage = 'Sending of ' + listType + ' member data to Mailchimp was not successful due to response: ' + data.trim(); logger.error(errorMessage); deferredTask.reject(errorMessage); }) } else { deferredTask.notify('No ' + listType + ' updates to send Mailchimp'); MemberService.all().then(function (refreshedMembers) { deferredTask.resolve(refreshedMembers); }); } return deferredTask.promise; }; function includeMemberInEmailList(listType, member) { if (member.email && member.mailchimpLists[listType].subscribed) { if (listType === 'socialEvents') { return member.groupMember && member.socialMember; } else { return member.groupMember; } } else { return false; } } function includeMemberInSubscription(listType, member) { return includeMemberInEmailList(listType, member) && !member.mailchimpLists[listType].updated; } function includeMemberInUnsubscription(listType, member) { if (!member || !member.groupMember) { return true; } else if (member.mailchimpLists) { if (listType === 'socialEvents') { return (!member.socialMember && member.mailchimpLists[listType].subscribed); } else { return (!member.mailchimpLists[listType].subscribed); } } else { return false; } } function includeSubscriberInUnsubscription(listType, allMembers, subscriber) { return includeMemberInUnsubscription(listType, responseToMember(listType, allMembers, subscriber)); } function resetUpdateStatusForMember(member) { // updated == false means not up to date with mail e.g. next list update will send this data to mailchimo member.mailchimpLists.walks.updated = false; member.mailchimpLists.socialEvents.updated = false; member.mailchimpLists.general.updated = false; } function responseToMember(listType, allMembers, mailchimpResponse) { return _(allMembers).find(function (member) { var matchedOnListSubscriberId = mailchimpResponse.leid && member.mailchimpLists[listType].leid && (mailchimpResponse.leid.toString() === member.mailchimpLists[listType].leid.toString()); var matchedOnLastReturnedEmail = member.mailchimpLists[listType].email && (mailchimpResponse.email.toLowerCase() === member.mailchimpLists[listType].email.toLowerCase()); var matchedOnCurrentEmail = member.email && mailchimpResponse.email.toLowerCase() === member.email.toLowerCase(); return (matchedOnListSubscriberId || matchedOnLastReturnedEmail || matchedOnCurrentEmail); }); } function findMemberAndMarkAsUpdated(listType, batchedMembers, response, deferredTask) { var member = responseToMember(listType, batchedMembers, response); if (member) { member.mailchimpLists[listType].leid = response.leid; member.mailchimpLists[listType].updated = true; // updated == true means up to date e.g. nothing to send to mailchimo member.mailchimpLists[listType].lastUpdated = DateUtils.nowAsValue(); member.mailchimpLists[listType].email = member.email; } else { deferredTask.notify('From ' + batchedMembers.length + ' members, could not find any member related to response ' + JSON.stringify(response)); } return member; } function processValidResponses(listType, validResponses, batchedMembers, savePromises, deferredTask) { _.each(validResponses, function (response) { var member = findMemberAndMarkAsUpdated(listType, batchedMembers, response, deferredTask); if (member) { delete member.mailchimpLists[listType].code; delete member.mailchimpLists[listType].error; deferredTask.notify('processing valid response for member ' + member.email); savePromises.push(member.$saveOrUpdate()); } }); } function processErrorResponses(listType, errorResponses, batchedMembers, savePromises, deferredTask) { _.each(errorResponses, function (response) { var member = findMemberAndMarkAsUpdated(listType, batchedMembers, response.email, deferredTask); if (member) { deferredTask.notify('processing error response for member ' + member.email); member.mailchimpLists[listType].code = response.code; member.mailchimpLists[listType].error = response.error; if (_.contains([210, 211, 212, 213, 214, 215, 220, 250], response.code)) member.mailchimpLists[listType].subscribed = false; savePromises.push(member.$saveOrUpdate()); } }); } return { responseToMember: responseToMember, defaultMailchimpSettings: defaultMailchimpSettings, createBatchSubscriptionForList: createBatchSubscriptionForList, resetAllBatchSubscriptions: resetAllBatchSubscriptions, resetUpdateStatusForMember: resetUpdateStatusForMember, addMailchimpIdentifiersToRequest: addMailchimpIdentifiersToRequest, includeMemberInSubscription: includeMemberInSubscription, includeMemberInEmailList: includeMemberInEmailList, includeSubscriberInUnsubscription: includeSubscriberInUnsubscription } }]); /* concatenated from client/src/app/js/expenses.js */ angular.module('ekwgApp') .controller('ExpensesController', ["$compile", "$log", "$timeout", "$sce", "$templateRequest", "$q", "$rootScope", "$location", "$routeParams", "$scope", "$filter", "DateUtils", "NumberUtils", "URLService", "LoggedInMemberService", "MemberService", "ContentMetaDataService", "ExpenseClaimsService", "MailchimpSegmentService", "MailchimpCampaignService", "MailchimpConfig", "Notifier", "EKWGFileUpload", function ($compile, $log, $timeout, $sce, $templateRequest, $q, $rootScope, $location, $routeParams, $scope, $filter, DateUtils, NumberUtils, URLService, LoggedInMemberService, MemberService, ContentMetaDataService, ExpenseClaimsService, MailchimpSegmentService, MailchimpCampaignService, MailchimpConfig, Notifier, EKWGFileUpload) { var logger = $log.getInstance('ExpensesController'); var noLogger = $log.getInstance('ExpensesControllerNoLogger'); $log.logLevels['ExpensesControllerNoLogger'] = $log.LEVEL.OFF; $log.logLevels['ExpensesController'] = $log.LEVEL.OFF; const SELECTED_EXPENSE = 'Expense from last email link'; $scope.receiptBaseUrl = ContentMetaDataService.baseUrl('expenseClaims'); $scope.dataError = false; $scope.members = []; $scope.expenseClaims = []; $scope.unfilteredExpenseClaims = []; $scope.expensesOpen = URLService.hasRouteParameter('expenseId') || URLService.isArea('expenses'); $scope.alertMessages = []; $scope.filterTypes = [{ disabled: !$routeParams.expenseId, description: SELECTED_EXPENSE, filter: function (expenseClaim) { if ($routeParams.expenseId) { return expenseClaim && expenseClaim.$id() === $routeParams.expenseId; } else { return false; } } }, { description: 'Unpaid expenses', filter: function (expenseClaim) { return !$scope.expenseClaimStatus(expenseClaim).atEndpoint; } }, { description: 'Paid expenses', filter: function (expenseClaim) { return $scope.expenseClaimStatus(expenseClaim).atEndpoint; } }, { description: 'Expenses awaiting action from me', filter: function (expenseClaim) { return LoggedInMemberService.allowFinanceAdmin() ? editable(expenseClaim) : editableAndOwned(expenseClaim); } }, { description: 'All expenses', filter: function () { return true; } }]; $scope.selected = { showOnlyMine: !allowAdminFunctions(), saveInProgress: false, expenseClaimIndex: 0, expenseItemIndex: 0, expenseFilter: $scope.filterTypes[$routeParams.expenseId ? 0 : 1] }; $scope.itemAlert = {}; var notify = Notifier($scope); var notifyItem = Notifier($scope.itemAlert); notify.setBusy(); var notificationsBaseUrl = 'partials/expenses/notifications'; LoggedInMemberService.showLoginPromptWithRouteParameter('expenseId'); $scope.showArea = function (area) { URLService.navigateTo('admin', area) }; $scope.selected.expenseClaim = function () { try { return $scope.expenseClaims[$scope.selected.expenseClaimIndex]; } catch (e) { console.error(e); } }; $scope.isInactive = function (expenseClaim) { return expenseClaim !== $scope.selected.expenseClaim(); }; $scope.selected.expenseItem = function () { try { var expenseClaim = $scope.expenseClaims[$scope.selected.expenseClaimIndex]; return expenseClaim ? expenseClaim.expenseItems[$scope.selected.expenseItemIndex] : undefined; } catch (e) { console.error(e); } }; $scope.expenseTypes = [ {value: "travel-reccie", name: "Travel (walk reccie)", travel: true}, {value: "travel-committee", name: "Travel (attend committee meeting)", travel: true}, {value: "other", name: "Other"}]; var eventTypes = { created: {description: "Created", editable: true}, submitted: {description: "Submitted", actionable: true, notifyCreator: true, notifyApprover: true}, 'first-approval': {description: "First Approval", actionable: true, notifyApprover: true}, 'second-approval': { description: "Second Approval", actionable: true, notifyCreator: true, notifyApprover: true, notifyTreasurer: true }, returned: {description: "Returned", atEndpoint: false, editable: true, notifyCreator: true, notifyApprover: true}, paid: {description: "Paid", atEndpoint: true, notifyCreator: true, notifyApprover: true, notifyTreasurer: true} }; var defaultExpenseClaim = function () { return _.clone({ "cost": 0, "expenseItems": [], "expenseEvents": [] }) }; var defaultExpenseItem = function () { return _.clone({ expenseType: $scope.expenseTypes[0], "travel": { "costPerMile": 0.28, "miles": 0, "from": '', "to": '', "returnJourney": true } }); }; function editable(expenseClaim) { return memberCanEditClaim(expenseClaim) && $scope.expenseClaimStatus(expenseClaim).editable; } function editableAndOwned(expenseClaim) { return memberOwnsClaim(expenseClaim) && $scope.expenseClaimStatus(expenseClaim).editable; } $scope.editable = function () { return editable($scope.selected.expenseClaim()); }; $scope.allowClearError = function () { return URLService.hasRouteParameter('expenseId') && $scope.dataError; }; $scope.allowAddExpenseClaim = function () { return !$scope.dataError && !_.find($scope.unfilteredExpenseClaims, editableAndOwned); }; $scope.allowFinanceAdmin = function () { return LoggedInMemberService.allowFinanceAdmin(); }; $scope.allowEditExpenseItem = function () { return $scope.allowAddExpenseItem() && $scope.selected.expenseItem() && $scope.selected.expenseClaim().$id(); }; $scope.allowAddExpenseItem = function () { return $scope.editable(); }; $scope.allowDeleteExpenseItem = function () { return $scope.allowEditExpenseItem(); }; $scope.allowDeleteExpenseClaim = function () { return !$scope.allowDeleteExpenseItem() && $scope.allowAddExpenseItem(); }; $scope.allowSubmitExpenseClaim = function () { return $scope.allowEditExpenseItem() && !$scope.allowResubmitExpenseClaim(); }; function allowAdminFunctions() { return LoggedInMemberService.allowTreasuryAdmin() || LoggedInMemberService.allowFinanceAdmin(); } $scope.allowAdminFunctions = function () { return allowAdminFunctions(); }; $scope.allowReturnExpenseClaim = function () { return $scope.allowAdminFunctions() && $scope.selected.expenseClaim() && expenseClaimHasEventType($scope.selected.expenseClaim(), eventTypes.submitted) && !expenseClaimHasEventType($scope.selected.expenseClaim(), eventTypes.returned) && $scope.expenseClaimStatus($scope.selected.expenseClaim()).actionable; }; $scope.allowResubmitExpenseClaim = function () { return $scope.editable() && expenseClaimHasEventType($scope.selected.expenseClaim(), eventTypes.returned); }; $scope.allowPaidExpenseClaim = function () { return LoggedInMemberService.allowTreasuryAdmin() && _.contains( [eventTypes.submitted.description, eventTypes['second-approval'].description, eventTypes['first-approval'].description], $scope.expenseClaimLatestEvent().eventType.description); }; function activeEvents(optionalEvents) { var events = optionalEvents || $scope.selected.expenseClaim().expenseEvents; var latestReturnedEvent = _.find(events.reverse(), function (event) { return _.isEqual(event.eventType, $scope.expenseClaimStatus.returned); }); return latestReturnedEvent ? events.slice(events.indexOf(latestReturnedEvent + 1)) : events; } function expenseClaimHasEventType(expenseClaim, eventType) { if (!expenseClaim) return false; return eventForEventType(expenseClaim, eventType); } function eventForEventType(expenseClaim, eventType) { if (expenseClaim) return _.find(expenseClaim.expenseEvents, function (event) { return _.isEqual(event.eventType, eventType); }); } $scope.allowApproveExpenseClaim = function () { return false; }; $scope.lastApprovedByMe = function () { var approvalEvents = $scope.approvalEvents(); return approvalEvents.length > 0 && _.last(approvalEvents).memberId === LoggedInMemberService.loggedInMember().memberId; }; $scope.approvalEvents = function () { if (!$scope.selected.expenseClaim()) return []; return _.filter($scope.selected.expenseClaim().expenseEvents, function (event) { return _.isEqual(event.eventType, eventTypes['first-approval']) || _.isEqual(event.eventType, eventTypes['second-approval']); }); }; $scope.expenseClaimStatus = function (optionalExpenseClaim) { var expenseClaim = optionalExpenseClaim || $scope.selected.expenseClaim(); return $scope.expenseClaimLatestEvent(expenseClaim).eventType; }; $scope.expenseClaimLatestEvent = function (optionalExpenseClaim) { var expenseClaim = optionalExpenseClaim || $scope.selected.expenseClaim(); return expenseClaim ? _.last(expenseClaim.expenseEvents) : {}; }; $scope.nextApprovalStage = function () { var approvals = $scope.approvalEvents(); if (approvals.length === 0) { return 'First Approval'; } else if (approvals.length === 1) { return 'Second Approval' } else { return 'Already has ' + approvals.length + ' approvals!'; } }; $scope.confirmApproveExpenseClaim = function () { var approvals = $scope.approvalEvents(); notifyItem.hide(); if (approvals.length === 0) { createEventAndSendNotifications(eventTypes['first-approval']); } else if (approvals.length === 1) { createEventAndSendNotifications(eventTypes['second-approval']); } else { notify.error('This expense claim already has ' + approvals.length + ' approvals!'); } }; $scope.showAllExpenseClaims = function () { $scope.dataError = false; $location.path('/admin/expenses') }; $scope.addExpenseClaim = function () { $scope.expenseClaims.unshift(new ExpenseClaimsService(defaultExpenseClaim())); $scope.selectExpenseClaim(0); createEvent(eventTypes.created); $scope.addExpenseItem(); }; $scope.selectExpenseItem = function (index) { if ($scope.selected.saveInProgress) { noLogger.info('selectExpenseItem - selected.saveInProgress - not changing to index', index); } else { noLogger.info('selectExpenseItem:', index); $scope.selected.expenseItemIndex = index; } }; $scope.selectExpenseClaim = function (index) { if ($scope.selected.saveInProgress) { noLogger.info('selectExpenseClaim - selected.saveInProgress - not changing to index', index); } else { $scope.selected.expenseClaimIndex = index; var expenseClaim = $scope.selected.expenseClaim(); noLogger.info('selectExpenseClaim:', index, expenseClaim); } }; $scope.editExpenseItem = function () { $scope.removeConfirm(); delete $scope.uploadedFile; $('#expense-detail-dialog').modal('show'); }; $scope.hideExpenseClaim = function () { $scope.removeConfirm(); $('#expense-detail-dialog').modal('hide'); }; $scope.addReceipt = function () { $('#hidden-input').click(); }; $scope.removeReceipt = function () { delete $scope.selected.expenseItem().receipt; delete $scope.uploadedFile; }; $scope.receiptTitle = function (expenseItem) { return expenseItem && expenseItem.receipt ? (expenseItem.receipt.title || expenseItem.receipt.originalFileName) : ''; }; function baseUrl() { return _.first($location.absUrl().split('/#')); } $scope.receiptUrl = function (expenseItem) { return expenseItem && expenseItem.receipt ? baseUrl() + $scope.receiptBaseUrl + '/' + expenseItem.receipt.awsFileName : ''; }; $scope.onFileSelect = function (file) { if (file) { $scope.uploadedFile = file; EKWGFileUpload.onFileSelect(file, notify, 'expenseClaims') .then(function (fileNameData) { var expenseItem = $scope.selected.expenseItem(); var oldTitle = (expenseItem.receipt && expenseItem.receipt.title) ? receipt.title : undefined; expenseItem.receipt = fileNameData; expenseItem.receipt.title = oldTitle; }); } }; function createEvent(eventType, reason) { var expenseClaim = $scope.selected.expenseClaim(); if (!expenseClaim.expenseEvents) expenseClaim.expenseEvents = []; var event = { "date": DateUtils.nowAsValue(), "memberId": LoggedInMemberService.loggedInMember().memberId, "eventType": eventType }; if (reason) event.reason = reason; expenseClaim.expenseEvents.push(event); } $scope.addExpenseItem = function () { $scope.removeConfirm(); var newExpenseItem = defaultExpenseItem(); $scope.selected.expenseClaim().expenseItems.push(newExpenseItem); var index = $scope.selected.expenseClaim().expenseItems.indexOf(newExpenseItem); if (index > -1) { $scope.selectExpenseItem(index); $scope.editExpenseItem(); } else { showExpenseErrorAlert('Could not display new expense item') } }; $scope.expenseTypeChange = function () { logger.debug('$scope.selected.expenseItem().expenseType', $scope.selected.expenseItem().expenseType); if ($scope.selected.expenseItem().expenseType.travel) { if (!$scope.selected.expenseItem().travel) $scope.selected.expenseItem().travel = defaultExpenseItem().travel; } else { delete $scope.selected.expenseItem().travel; } $scope.setExpenseItemFields(); }; $scope.expenseDateCalendar = { open: function ($event) { $scope.expenseDateCalendar.opened = true; } }; function recalculateClaimCost() { $scope.selected.expenseClaim().cost = $filter('sumValues')($scope.selected.expenseClaim().expenseItems, 'cost'); } $scope.cancelExpenseChange = function () { $scope.refreshExpenses().then($scope.hideExpenseClaim).then(notify.clearBusy); }; function showExpenseErrorAlert(message) { var messageDefaulted = message || 'Please try this again.'; notify.error('Your expense claim could not be saved. ' + messageDefaulted); $scope.selected.saveInProgress = false; } function showExpenseEmailErrorAlert(message) { $scope.selected.saveInProgress = false; notify.error('Your expense claim email processing failed. ' + message); } function showExpenseProgressAlert(message, busy) { notify.progress(message, busy); } function showExpenseSuccessAlert(message, busy) { notify.success(message, busy); } $scope.saveExpenseClaim = function (optionalExpenseClaim) { $scope.selected.saveInProgress = true; function showExpenseSaved(data) { $scope.expenseClaims[$scope.selected.expenseClaimIndex] = data; $scope.selected.saveInProgress = false; return notify.success('Expense was saved successfully'); } showExpenseProgressAlert('Saving expense claim', true); $scope.setExpenseItemFields(); return (optionalExpenseClaim || $scope.selected.expenseClaim()).$saveOrUpdate(showExpenseSaved, showExpenseSaved, showExpenseErrorAlert, showExpenseErrorAlert) .then($scope.hideExpenseClaim) .then(notify.clearBusy); }; $scope.approveExpenseClaim = function () { $scope.confirmAction = {approve: true}; if ($scope.lastApprovedByMe()) notifyItem.warning({ title: 'Duplicate approval warning', message: 'You were the previous approver, therefore ' + $scope.nextApprovalStage() + ' ought to be carried out by someone else. Are you sure you want to do this?' }); }; $scope.deleteExpenseClaim = function () { $scope.confirmAction = {delete: true}; }; $scope.deleteExpenseItem = function () { $scope.confirmAction = {delete: true}; }; $scope.confirmDeleteExpenseItem = function () { $scope.selected.saveInProgress = true; showExpenseProgressAlert('Deleting expense item', true); var expenseItem = $scope.selected.expenseItem(); logger.debug('removing', expenseItem); var index = $scope.selected.expenseClaim().expenseItems.indexOf(expenseItem); if (index > -1) { $scope.selected.expenseClaim().expenseItems.splice(index, 1); } else { showExpenseErrorAlert('Could not delete expense item') } $scope.selectExpenseItem(0); recalculateClaimCost(); $scope.saveExpenseClaim() .then($scope.removeConfirm) .then(notify.clearBusy); }; $scope.removeConfirm = function () { delete $scope.confirmAction; showExpenseSuccessAlert(); }; $scope.confirmDeleteExpenseClaim = function () { showExpenseProgressAlert('Deleting expense claim', true); function showExpenseDeleted() { return showExpenseSuccessAlert('Expense was deleted successfully'); } $scope.selected.expenseClaim().$remove(showExpenseDeleted, showExpenseDeleted, showExpenseErrorAlert, showExpenseErrorAlert) .then($scope.hideExpenseClaim) .then(showExpenseDeleted) .then($scope.refreshExpenses) .then($scope.removeConfirm) .then(notify.clearBusy); }; $scope.submitExpenseClaim = function (state) { $scope.resubmit = state; $('#submit-dialog').modal('show'); }; function hideSubmitDialog() { $('#submit-dialog').modal('hide'); $scope.resubmit = false; } $scope.cancelSubmitExpenseClaim = function () { hideSubmitDialog(); }; $scope.returnExpenseClaim = function () { $('#return-dialog').modal('show'); }; $scope.confirmReturnExpenseClaim = function (reason) { hideReturnDialog(); return createEventAndSendNotifications(eventTypes.returned, reason); }; function hideReturnDialog() { $('#return-dialog').modal('hide'); } $scope.cancelReturnExpenseClaim = function () { hideReturnDialog(); }; $scope.paidExpenseClaim = function () { $('#paid-dialog').modal('show'); }; $scope.confirmPaidExpenseClaim = function () { createEventAndSendNotifications(eventTypes.paid) .then(hidePaidDialog); }; function hidePaidDialog() { $('#paid-dialog').modal('hide'); } $scope.cancelPaidExpenseClaim = function () { hidePaidDialog(); }; $scope.confirmSubmitExpenseClaim = function () { if ($scope.resubmit) $scope.selected.expenseClaim().expenseEvents = [eventForEventType($scope.selected.expenseClaim(), eventTypes.created)]; createEventAndSendNotifications(eventTypes.submitted); }; $scope.resubmitExpenseClaim = function () { $scope.submitExpenseClaim(true); }; $scope.expenseClaimCreatedEvent = function (optionalExpenseClaim) { return eventForEventType(optionalExpenseClaim || $scope.selected.expenseClaim(), eventTypes.created); }; function createEventAndSendNotifications(eventType, reason) { notify.setBusy(); $scope.selected.saveInProgress = true; var expenseClaim = $scope.selected.expenseClaim(); var expenseClaimCreatedEvent = $scope.expenseClaimCreatedEvent(expenseClaim); return $q.when(createEvent(eventType, reason)) .then(sendNotificationsToAllRoles, showExpenseEmailErrorAlert) .then($scope.saveExpenseClaim, showExpenseEmailErrorAlert, showExpenseProgressAlert); function renderTemplateContent(templateData) { var task = $q.defer(); var templateFunction = $compile(templateData); var templateElement = templateFunction($scope); $timeout(function () { $scope.$digest(); task.resolve(templateElement.html()); }); return task.promise; } function sendNotificationsToAllRoles() { return LoggedInMemberService.getMemberForMemberId(expenseClaimCreatedEvent.memberId) .then(function (member) { logger.debug('sendNotification:', 'memberId', expenseClaimCreatedEvent.memberId, 'member', member); var memberFullName = $filter('fullNameWithAlias')(member); return $q.when(showExpenseProgressAlert('Preparing to email ' + memberFullName)) .then(hideSubmitDialog, showExpenseEmailErrorAlert, showExpenseProgressAlert) .then(sendCreatorNotifications, showExpenseEmailErrorAlert, showExpenseProgressAlert) .then(sendApproverNotifications, showExpenseEmailErrorAlert, showExpenseProgressAlert) .then(sendTreasurerNotifications, showExpenseEmailErrorAlert, showExpenseProgressAlert); function sendCreatorNotifications() { if (eventType.notifyCreator) return sendNotificationsTo({ templateUrl: templateForEvent('creator', eventType), memberIds: [expenseClaimCreatedEvent.memberId], segmentType: 'directMail', segmentNameSuffix: '', destination: 'creator' }); return false; } function sendApproverNotifications() { if (eventType.notifyApprover) return sendNotificationsTo({ templateUrl: templateForEvent('approver', eventType), memberIds: MemberService.allMemberIdsWithPrivilege('financeAdmin', $scope.members), segmentType: 'expenseApprover', segmentNameSuffix: 'approval ', destination: 'approvers' }); return false; } function sendTreasurerNotifications() { if (eventType.notifyTreasurer) return sendNotificationsTo({ templateUrl: templateForEvent('treasurer', eventType), memberIds: MemberService.allMemberIdsWithPrivilege('treasuryAdmin', $scope.members), segmentType: 'expenseTreasurer', segmentNameSuffix: 'payment ', destination: 'treasurer' }); return false; } function templateForEvent(role, eventType) { return notificationsBaseUrl + '/' + role + '/' + eventType.description.toLowerCase().replace(' ', '-') + '-notification.html'; } function sendNotificationsTo(templateAndNotificationMembers) { logger.debug('sendNotificationsTo:', templateAndNotificationMembers); var campaignName = 'Expense ' + eventType.description + ' notification (to ' + templateAndNotificationMembers.destination + ')'; var campaignNameAndMember = campaignName + ' (' + memberFullName + ')'; var segmentName = 'Expense notification ' + templateAndNotificationMembers.segmentNameSuffix + '(' + memberFullName + ')'; if (templateAndNotificationMembers.memberIds.length === 0) throw new Error('No members have been configured as ' + templateAndNotificationMembers.destination + ' therefore notifications for this step will fail!!'); return $templateRequest($sce.getTrustedResourceUrl(templateAndNotificationMembers.templateUrl)) .then(renderTemplateContent) .then(populateContentSections) .then(sendNotification(templateAndNotificationMembers)) .catch(showExpenseEmailErrorAlert); function populateContentSections(expenseNotificationText) { return { sections: { expense_id_url: 'Please click <a href="' + baseUrl() + '/#/admin/expenseId/' + expenseClaim.$id() + '" target="_blank">this link</a> to see the details of the above expense claim, or to make changes to it.', expense_notification_text: expenseNotificationText } }; } function sendNotification(templateAndNotificationMembers) { return function (contentSections) { return createOrSaveMailchimpSegment() .then(saveSegmentDataToMember, showExpenseEmailErrorAlert, showExpenseProgressAlert) .then(sendEmailCampaign, showExpenseEmailErrorAlert, showExpenseProgressAlert) .then(notifyEmailSendComplete, showExpenseEmailErrorAlert, showExpenseSuccessAlert); function createOrSaveMailchimpSegment() { return MailchimpSegmentService.saveSegment('general', {segmentId: MailchimpSegmentService.getMemberSegmentId(member, templateAndNotificationMembers.segmentType)}, templateAndNotificationMembers.memberIds, segmentName, $scope.members); } function saveSegmentDataToMember(segmentResponse) { MailchimpSegmentService.setMemberSegmentId(member, templateAndNotificationMembers.segmentType, segmentResponse.segment.id); return LoggedInMemberService.saveMember(member); } function sendEmailCampaign() { showExpenseProgressAlert('Sending ' + campaignNameAndMember); return MailchimpConfig.getConfig() .then(function (config) { var campaignId = config.mailchimp.campaigns.expenseNotification.campaignId; var segmentId = MailchimpSegmentService.getMemberSegmentId(member, templateAndNotificationMembers.segmentType); logger.debug('about to replicateAndSendWithOptions with campaignName', campaignNameAndMember, 'campaign Id', campaignId, 'segmentId', segmentId); return MailchimpCampaignService.replicateAndSendWithOptions({ campaignId: campaignId, campaignName: campaignNameAndMember, contentSections: contentSections, segmentId: segmentId }); }) .then(function () { showExpenseProgressAlert('Sending of ' + campaignNameAndMember + ' was successful', true); }); } function notifyEmailSendComplete() { showExpenseSuccessAlert('Sending of ' + campaignName + ' was successful. Check your inbox for progress.'); } } } } }); } } $scope.setExpenseItemFields = function () { var expenseItem = $scope.selected.expenseItem(); if (expenseItem) { expenseItem.expenseDate = DateUtils.asValueNoTime(expenseItem.expenseDate); if (expenseItem.travel) expenseItem.travel.miles = NumberUtils.asNumber(expenseItem.travel.miles); expenseItem.description = expenseItemDescription(expenseItem); expenseItem.cost = expenseItemCost(expenseItem); } recalculateClaimCost(); }; $scope.prefixedExpenseItemDescription = function (expenseItem) { if (!expenseItem) return ''; var prefix = expenseItem.expenseType && expenseItem.expenseType.travel ? expenseItem.expenseType.name + ' - ' : ''; return prefix + expenseItem.description; }; function expenseItemDescription(expenseItem) { var description; if (!expenseItem) return ''; if (expenseItem.travel && expenseItem.expenseType.travel) { description = [ expenseItem.travel.from, 'to', expenseItem.travel.to, expenseItem.travel.returnJourney ? 'return trip' : 'single trip', '(' + expenseItem.travel.miles, 'miles', expenseItem.travel.returnJourney ? 'x 2' : '', 'x', parseInt(expenseItem.travel.costPerMile * 100) + 'p per mile)' ].join(' '); } else { description = expenseItem.description; } return description; } function expenseItemCost(expenseItem) { var cost; if (!expenseItem) return 0; if (expenseItem.travel && expenseItem.expenseType.travel) { cost = (NumberUtils.asNumber(expenseItem.travel.miles) * (expenseItem.travel.returnJourney ? 2 : 1) * NumberUtils.asNumber(expenseItem.travel.costPerMile)); } else { cost = expenseItem.cost; } noLogger.info(cost, 'from expenseItem=', expenseItem); return NumberUtils.asNumber(cost, 2); } function refreshMembers() { if (LoggedInMemberService.memberLoggedIn()) { notify.progress('Refreshing member data...'); return MemberService.allLimitedFields(MemberService.filterFor.GROUP_MEMBERS).then(function (members) { logger.debug('refreshMembers: found', members.length, 'members'); return $scope.members = members; }); } } function memberCanEditClaim(expenseClaim) { if (!expenseClaim) return false; return memberOwnsClaim(expenseClaim) || LoggedInMemberService.allowFinanceAdmin(); } function memberOwnsClaim(expenseClaim) { if (!expenseClaim) return false; return (LoggedInMemberService.loggedInMember().memberId === $scope.expenseClaimCreatedEvent(expenseClaim).memberId); } $scope.refreshExpenses = function () { $scope.dataError = false; logger.debug('refreshExpenses started'); notify.setBusy(); notify.progress('Filtering for ' + $scope.selected.expenseFilter.description + '...'); logger.debug('refreshing expenseFilter', $scope.selected.expenseFilter); let noExpenseFound = function () { $scope.dataError = true; return notify.warning({ title: 'Expense claim could not be found', message: 'Try opening again from the link in the notification email, or click Show All Expense Claims' }) }; function query() { if ($scope.selected.expenseFilter.description === SELECTED_EXPENSE && $routeParams.expenseId) { return ExpenseClaimsService.getById($routeParams.expenseId) .then(function (expense) { if (!expense) { return noExpenseFound(); } else { return [expense]; } }) .catch(noExpenseFound); } else { return ExpenseClaimsService.all(); } } return query() .then(function (expenseClaims) { $scope.unfilteredExpenseClaims = []; $scope.expenseClaims = _.chain(expenseClaims).filter(function (expenseClaim) { return $scope.allowAdminFunctions() ? ($scope.selected.showOnlyMine ? memberOwnsClaim(expenseClaim) : true) : memberCanEditClaim(expenseClaim); }).filter(function (expenseClaim) { $scope.unfilteredExpenseClaims.push(expenseClaim); return $scope.selected.expenseFilter.filter(expenseClaim); }).sortBy(function (expenseClaim) { var expenseClaimLatestEvent = $scope.expenseClaimLatestEvent(expenseClaim); return expenseClaimLatestEvent ? expenseClaimLatestEvent.date : true; }).reverse().value(); let outcome = 'Found ' + $scope.expenseClaims.length + ' expense claim(s)'; notify.progress(outcome); logger.debug('refreshExpenses finished', outcome); notify.clearBusy(); return $scope.expenseClaims; }, notify.error) .catch(notify.error); }; $q.when(refreshMembers()) .then($scope.refreshExpenses) .then(notify.setReady) .catch(notify.error); }] ); /* concatenated from client/src/app/js/filters.js */ angular.module('ekwgApp') .factory('FilterUtils', function () { return { nameFilter: function (alias) { return alias ? 'fullNameWithAlias' : 'fullName'; } }; }) .filter('keepLineFeeds', function () { return function (input) { if (!input) return input; return input .replace(/(\r\n|\r|\n)/g, '<br/>') .replace(/\t/g, '&nbsp;&nbsp;&nbsp;') .replace(/ /g, '&nbsp;'); } }) .filter('lineFeedsToBreaks', function () { return function (input) { if (!input) return input; return input .replace(/(\r\n|\r|\n)/g, '<br/>') } }) .filter('displayName', function () { return function (member) { return member === undefined ? null : (member.firstName + ' ' + (member.hideSurname ? '' : member.lastName)).trim(); } }) .filter('fullName', function () { return function (member, defaultValue) { return member === undefined ? defaultValue || '(deleted member)' : (member.firstName + ' ' + member.lastName).trim(); } }) .filter('fullNameWithAlias', ["$filter", function ($filter) { return function (member, defaultValue) { return member ? ($filter('fullName')(member, defaultValue)) + (member.nameAlias ? ' (' + member.nameAlias + ')' : '') : defaultValue; } }]) .filter('fullNameWithAliasOrMe', ["$filter", "LoggedInMemberService", function ($filter, LoggedInMemberService) { return function (member, defaultValue, memberId) { return member ? (LoggedInMemberService.loggedInMember().memberId === member.$id() && member.$id() === memberId ? "Me" : ($filter('fullName')(member, defaultValue)) + (member.nameAlias ? ' (' + member.nameAlias + ')' : '')) : defaultValue; } }]) .filter('firstName', ["$filter", function ($filter) { return function (member, defaultValue) { return s.words($filter('fullName')(member, defaultValue))[0]; } }]) .filter('memberIdsToFullNames', ["$filter", function ($filter) { return function (memberIds, members, defaultValue) { return _(memberIds).map(function (memberId) { return $filter('memberIdToFullName')(memberId, members, defaultValue); }).join(', '); } }]) .filter('memberIdToFullName', ["$filter", "MemberService", "FilterUtils", function ($filter, MemberService, FilterUtils) { return function (memberId, members, defaultValue, alias) { return $filter(FilterUtils.nameFilter(alias))(MemberService.toMember(memberId, members), defaultValue); } }]) .filter('memberIdToFirstName', ["$filter", "MemberService", function ($filter, MemberService) { return function (memberId, members, defaultValue) { return $filter('firstName')(MemberService.toMember(memberId, members), defaultValue); } }]) .filter('asMoney', ["NumberUtils", function (NumberUtils) { return function (number) { return isNaN(number) ? '' : '£' + NumberUtils.asNumber(number).toFixed(2); } }]) .filter('humanize', function () { return function (string) { return s.humanize(string); } }) .filter('sumValues', ["NumberUtils", function (NumberUtils) { return function (items, propertyName) { return NumberUtils.sumValues(items, propertyName); } }]) .filter('walkSummary', ["$filter", function ($filter) { return function (walk) { return walk === undefined ? null : $filter('displayDate')(walk.walkDate) + " led by " + (walk.displayName || walk.contactName || "unknown") + " (" + (walk.briefDescriptionAndStartPoint || 'no description') + ')'; } }]) .filter('meetupEventSummary', ["$filter", function ($filter) { return function (meetupEvent) { return meetupEvent ? $filter('displayDate')(meetupEvent.startTime) + " (" + meetupEvent.title + ')' : null; } }]) .filter('asWalkEventType', ["WalksReferenceService", function (WalksReferenceService) { return function (eventTypeString, field) { var eventType = WalksReferenceService.toEventType(eventTypeString); return eventType && field ? eventType[field] : eventType; } }]) .filter('asEventNote', function () { return function (event) { return _.compact([event.description, event.reason]).join(', '); } }) .filter('asChangedItemsTooltip', ["$filter", function ($filter) { return function (event, members) { return _(event.data).map(function (value, key) { return s.humanize(key) + ': ' + $filter('toAuditDeltaValue')(value, key, members); }).join(', '); } }]) .filter('valueOrDefault', function () { return function (value, defaultValue) { return value || defaultValue || '(none)'; } }) .filter('toAuditDeltaValue', ["$filter", function ($filter) { return function (value, fieldName, members, defaultValue) { switch (fieldName) { case 'walkDate': return $filter('displayDate')(value); case 'walkLeaderMemberId': return $filter('memberIdToFullName')(value, members, defaultValue); default: return $filter('valueOrDefault')(value, defaultValue); } } }]) .filter('toAuditDeltaChangedItems', function () { return function (dataAuditDeltaInfoItems) { return _(dataAuditDeltaInfoItems).pluck('fieldName').map(s.humanize).join(', '); } }) .filter('asWalkValidationsList', function () { return function (walkValidations) { var lastItem = _.last(walkValidations); var firstItems = _.without(walkValidations, lastItem); var joiner = firstItems.length > 0 ? ' and ' : ''; return firstItems.join(', ') + joiner + lastItem; } }) .filter('idFromRecord', function () { return function (mongoRecord) { return mongoRecord.$id; } }) .filter('eventTimes', function () { return function (socialEvent) { var eventTimes = socialEvent.eventTimeStart; if (socialEvent.eventTimeEnd) eventTimes += ' - ' + socialEvent.eventTimeEnd; return eventTimes; } }) .filter('displayDate', ["DateUtils", function (DateUtils) { return function (dateValue) { return DateUtils.displayDate(dateValue); } }]) .filter('displayDay', ["DateUtils", function (DateUtils) { return function (dateValue) { return DateUtils.displayDay(dateValue); } }]) .filter('displayDates', ["$filter", function ($filter) { return function (dateValues) { return _(dateValues).map(function (dateValue) { return $filter('displayDate')(dateValue); }).join(', '); } }]) .filter('displayDateAndTime', ["DateUtils", function (DateUtils) { return function (dateValue) { return DateUtils.displayDateAndTime(dateValue); } }]) .filter('fromExcelDate', ["DateUtils", function (DateUtils) { return function (dateValue) { return DateUtils.displayDate(dateValue); } }]) .filter('lastLoggedInDateDisplayed', ["DateUtils", function (DateUtils) { return function (dateValue) { return DateUtils.displayDateAndTime(dateValue); } }]) .filter('lastConfirmedDateDisplayed', ["DateUtils", function (DateUtils) { return function (member) { return member && member.profileSettingsConfirmedAt ? 'by ' + (member.profileSettingsConfirmedBy || 'member') + ' at ' + DateUtils.displayDateAndTime(member.profileSettingsConfirmedAt) : 'not confirmed yet'; } }]) .filter('createdAudit', ["StringUtils", function (StringUtils) { return function (resource, members) { return StringUtils.formatAudit(resource.createdBy, resource.createdDate, members) } }]) .filter('updatedAudit', ["StringUtils", function (StringUtils) { return function (resource, members) { return StringUtils.formatAudit(resource.updatedBy, resource.updatedDate, members) } }]); /* concatenated from client/src/app/js/forgotPasswordController.js */ angular.module("ekwgApp") .controller("ForgotPasswordController", ["$q", "$log", "$scope", "$rootScope", "$location", "$routeParams", "EmailSubscriptionService", "MemberService", "LoggedInMemberService", "URLService", "MailchimpConfig", "MailchimpSegmentService", "MailchimpCampaignService", "Notifier", "ValidationUtils", "close", function ($q, $log, $scope, $rootScope, $location, $routeParams, EmailSubscriptionService, MemberService, LoggedInMemberService, URLService, MailchimpConfig, MailchimpSegmentService, MailchimpCampaignService, Notifier, ValidationUtils, close) { var logger = $log.getInstance("ForgotPasswordController"); $log.logLevels["ForgotPasswordController"] = $log.LEVEL.OFF; $scope.notify = {}; var notify = Notifier($scope.notify); $scope.showSubmit = true; $scope.FORGOTTEN_PASSWORD_SEGMENT = "Forgotten Password"; $scope.forgottenPasswordCredentials = {}; $scope.actions = { close: function () { close(); }, submittable: function () { var onePopulated = ValidationUtils.fieldPopulated($scope.forgottenPasswordCredentials, "credentialOne"); var twoPopulated = ValidationUtils.fieldPopulated($scope.forgottenPasswordCredentials, "credentialTwo"); logger.info("notSubmittable: onePopulated", onePopulated, "twoPopulated", twoPopulated); return twoPopulated && onePopulated; }, submit: function () { var userDetails = "User Name " + $scope.forgottenPasswordCredentials.credentialOne + " and Membership Number " + $scope.forgottenPasswordCredentials.credentialTwo; notify.setBusy(); $scope.showSubmit = false; notify.success("Checking our records for " + userDetails, true); if ($scope.forgottenPasswordCredentials.credentialOne.length === 0 || $scope.forgottenPasswordCredentials.credentialTwo.length === 0) { $scope.showSubmit = true; notify.error({ title: "Incorrect information entered", message: "Please enter both a User Name and a Membership Number" }); } else { var forgotPasswordData = {loginResponse: {memberLoggedIn: false}}; var message; LoggedInMemberService.getMemberForResetPassword($scope.forgottenPasswordCredentials.credentialOne, $scope.forgottenPasswordCredentials.credentialTwo) .then(function (member) { if (_.isEmpty(member)) { message = "No member was found with " + userDetails; forgotPasswordData.loginResponse.alertMessage = message; $scope.showSubmit = true; return { forgotPasswordData: forgotPasswordData, notifyObject: { title: "Incorrect information entered", message: message } }; } else if (!member.mailchimpLists.general.subscribed) { message = "Sorry, " + userDetails + " is not setup in our system to receive emails"; forgotPasswordData.member = member; forgotPasswordData.loginResponse.alertMessage = message; $scope.showSubmit = true; return { forgotPasswordData: forgotPasswordData, notifyObject: { title: "Message cannot be sent", message: message } }; } else { LoggedInMemberService.setPasswordResetId(member); EmailSubscriptionService.resetUpdateStatusForMember(member); logger.debug("saving member", member); $scope.forgottenPasswordMember = member; member.$saveOrUpdate(sendForgottenPasswordEmailToMember, sendForgottenPasswordEmailToMember, saveFailed, saveFailed); forgotPasswordData.member = member; forgotPasswordData.loginResponse.alertMessage = "New password requested from login screen"; return {forgotPasswordData: forgotPasswordData}; } }).then(function (response) { return LoggedInMemberService.auditMemberLogin($scope.forgottenPasswordCredentials.credentialOne, "", response.forgotPasswordData.member, response.forgotPasswordData.loginResponse) .then(function () { if (response.notifyObject) { notify.error(response.notifyObject) } }); }); } } }; function saveFailed(error) { notify.error({title: "The password reset failed", message: error}); } function getMailchimpConfig() { return MailchimpConfig.getConfig() .then(function (config) { $scope.mailchimpConfig = config.mailchimp; }); } function createOrSaveForgottenPasswordSegment() { return MailchimpSegmentService.saveSegment("general", {segmentId: $scope.mailchimpConfig.segments.general.forgottenPasswordSegmentId}, [{id: $scope.forgottenPasswordMember.$id()}], $scope.FORGOTTEN_PASSWORD_SEGMENT, [$scope.forgottenPasswordMember]); } function saveSegmentDataToMailchimpConfig(segmentResponse) { return MailchimpConfig.getConfig() .then(function (config) { config.mailchimp.segments.general.forgottenPasswordSegmentId = segmentResponse.segment.id; MailchimpConfig.saveConfig(config); }); } function sendForgottenPasswordCampaign() { var member = $scope.forgottenPasswordMember.firstName + " " + $scope.forgottenPasswordMember.lastName; return MailchimpConfig.getConfig() .then(function (config) { logger.debug("config.mailchimp.campaigns.forgottenPassword.campaignId", config.mailchimp.campaigns.forgottenPassword.campaignId); logger.debug("config.mailchimp.segments.general.forgottenPasswordSegmentId", config.mailchimp.segments.general.forgottenPasswordSegmentId); return MailchimpCampaignService.replicateAndSendWithOptions({ campaignId: config.mailchimp.campaigns.forgottenPassword.campaignId, campaignName: "EKWG website password reset instructions (" + member + ")", segmentId: config.mailchimp.segments.general.forgottenPasswordSegmentId }); }); } function updateGeneralList() { return EmailSubscriptionService.createBatchSubscriptionForList("general", [$scope.forgottenPasswordMember]); } function sendForgottenPasswordEmailToMember() { $q.when(notify.success("Sending forgotten password email")) .then(updateGeneralList) .then(getMailchimpConfig) .then(createOrSaveForgottenPasswordSegment) .then(saveSegmentDataToMailchimpConfig) .then(sendForgottenPasswordCampaign) .then(finalMessage) .then(notify.clearBusy) .catch(handleSendError); } function handleSendError(errorResponse) { notify.error({ title: "Your email could not be sent", message: (errorResponse.message || errorResponse) + (errorResponse.error ? (". Error was: " + ErrorMessageService.stringify(errorResponse.error)) : "") }); } function finalMessage() { return notify.success({ title: "Message sent", message: "We've sent a message to the email address we have for you. Please check your inbox and follow the instructions in the message." }) } }] ); /* concatenated from client/src/app/js/googleMapsServices.js */ angular.module('ekwgApp') .factory('GoogleMapsConfig', ["$http", "HTTPResponseService", function ($http, HTTPResponseService) { function getConfig() { return $http.get('/googleMaps/config').then(function (response) { return HTTPResponseService.returnResponse(response); }); } return { getConfig: getConfig, } }]); /* concatenated from client/src/app/js/homeController.js */ angular.module('ekwgApp') .controller('HomeController', ["$log", "$scope", "$routeParams", "LoggedInMemberService", "ContentMetaDataService", "CommitteeReferenceData", "InstagramService", "SiteEditService", function ($log, $scope, $routeParams, LoggedInMemberService, ContentMetaDataService, CommitteeReferenceData, InstagramService, SiteEditService) { var logger = $log.getInstance('HomeController'); $log.logLevels['HomeController'] = $log.LEVEL.OFF; $scope.feeds = {instagram: {recentMedia: []}, facebook: {}}; ContentMetaDataService.getMetaData('imagesHome') .then(function (contentMetaData) { $scope.interval = 5000; $scope.slides = contentMetaData.files; }); InstagramService.recentMedia() .then(function (recentMediaResponse) { $scope.feeds.instagram.recentMedia = _.take(recentMediaResponse.instagram, 14); logger.debug("Refreshed social media", $scope.feeds.instagram.recentMedia, 'count =', $scope.feeds.instagram.recentMedia.length); }); $scope.mediaUrlFor = function (media) { logger.debug('mediaUrlFor:media', media); return (media && media.images) ? media.images.standard_resolution.url : ""; }; $scope.mediaCaptionFor = function (media) { logger.debug('mediaCaptionFor:media', media); return media ? media.caption.text : ""; }; $scope.allowEdits = function () { return SiteEditService.active() && LoggedInMemberService.allowContentEdits(); }; }]); /* concatenated from client/src/app/js/howTo.js */ angular.module('ekwgApp') .controller("HowToDialogController", ["$rootScope", "$log", "$q", "$scope", "$filter", "FileUtils", "DateUtils", "EKWGFileUpload", "DbUtils", "LoggedInMemberService", "ErrorMessageService", "MailchimpLinkService", "MailchimpCampaignService", "Notifier", "MemberResourcesReferenceData", "memberResource", "close", function ($rootScope, $log, $q, $scope, $filter, FileUtils, DateUtils, EKWGFileUpload, DbUtils, LoggedInMemberService, ErrorMessageService, MailchimpLinkService, MailchimpCampaignService, Notifier, MemberResourcesReferenceData, memberResource, close) { var logger = $log.getInstance("HowToDialogController"); $log.logLevels["HowToDialogController"] = $log.LEVEL.OFF; $scope.notify = {}; var notify = Notifier($scope.notify); notify.setBusy(); $scope.fileUtils = FileUtils; $scope.mailchimpLinkService = MailchimpLinkService; $scope.memberResourcesReferenceData = MemberResourcesReferenceData; $scope.memberResource = memberResource; logger.debug("memberResourcesReferenceData:", $scope.memberResourcesReferenceData, "memberResource:", memberResource); $scope.resourceDateCalendar = { open: function () { $scope.resourceDateCalendar.opened = true; } }; $scope.cancel = function () { close(); }; $scope.onSelect = function (file) { if (file) { logger.debug("onSelect:file:about to upload ->", file); $scope.uploadedFile = file; EKWGFileUpload.onFileSelect(file, notify, "memberResources") .then(function (fileNameData) { logger.debug("onSelect:file:upload complete -> fileNameData", fileNameData); $scope.memberResource.data.fileNameData = fileNameData; $scope.memberResource.data.fileNameData.title = $scope.oldTitle || file.name; }); } }; $scope.attach = function (file) { $("#hidden-input").click(); }; $scope.save = function () { notify.setBusy(); logger.debug("save ->", $scope.memberResource); return $scope.memberResource.$saveOrUpdate(notify.success, notify.success, notify.error, notify.error) .then($scope.hideDialog) .then(notify.clearBusy) .catch(handleError); function handleError(errorResponse) { notify.error({ title: "Your changes could not be saved", message: (errorResponse && errorResponse.error ? (". Error was: " + JSON.stringify(errorResponse.error)) : "") }); notify.clearBusy(); } }; $scope.cancelChange = function () { $q.when($scope.hideDialog()).then(notify.clearBusy); }; $scope.campaignDate = function (campaign) { return DateUtils.asValueNoTime(campaign.send_time || campaign.create_time); }; $scope.campaignTitle = function (campaign) { return campaign.title + " (" + $filter("displayDate")($scope.campaignDate(campaign)) + ")"; }; $scope.campaignChange = function () { logger.debug("campaignChange:memberResource.data.campaign", $scope.memberResource.data.campaign); if ($scope.memberResource.data.campaign) { $scope.memberResource.title = $scope.memberResource.data.campaign.title; $scope.memberResource.resourceDate = $scope.campaignDate($scope.memberResource.data.campaign); } }; $scope.performCampaignSearch = function (selectFirst) { var campaignSearchTerm = $scope.memberResource.data.campaignSearchTerm; if (campaignSearchTerm) { notify.setBusy(); notify.progress({ title: "Email search", message: "searching for campaigns matching '" + campaignSearchTerm + "'" }); var options = { limit: $scope.memberResource.data.campaignSearchLimit, concise: true, status: "sent", campaignSearchTerm: campaignSearchTerm }; options[$scope.memberResource.data.campaignSearchField] = campaignSearchTerm; return MailchimpCampaignService.list(options).then(function (response) { $scope.campaigns = response.data; if (selectFirst) { $scope.memberResource.data.campaign = _.first($scope.campaigns); $scope.campaignChange(); } else { logger.debug("$scope.memberResource.data.campaign", $scope.memberResource.data.campaign, "first campaign=", _.first($scope.campaigns)) } logger.debug("response.data", response.data); notify.success({ title: "Email search", message: "Found " + $scope.campaigns.length + " campaigns matching '" + campaignSearchTerm + "'" }); notify.clearBusy(); return true; }); } else { return $q.when(true); } }; $scope.hideDialog = function () { $rootScope.$broadcast("memberResourcesChanged"); close(); }; $scope.editMode = $scope.memberResource.$id() ? "Edit" : "Add"; logger.debug("editMode:", $scope.editMode); if ($scope.memberResource.resourceType === "email" && $scope.memberResource.$id()) { $scope.performCampaignSearch(false).then(notify.clearBusy) } else { notify.clearBusy(); } }]) .controller("HowToController", ["$rootScope", "$window", "$log", "$sce", "$timeout", "$templateRequest", "$compile", "$q", "$scope", "$filter", "$routeParams", "$location", "URLService", "DateUtils", "MailchimpLinkService", "FileUtils", "NumberUtils", "LoggedInMemberService", "MemberService", "ContentMetaDataService", "MailchimpSegmentService", "MailchimpCampaignService", "MemberResourcesReferenceData", "MailchimpConfig", "Notifier", "MemberResourcesService", "CommitteeReferenceData", "ModalService", "SiteEditService", function ($rootScope, $window, $log, $sce, $timeout, $templateRequest, $compile, $q, $scope, $filter, $routeParams, $location, URLService, DateUtils, MailchimpLinkService, FileUtils, NumberUtils, LoggedInMemberService, MemberService, ContentMetaDataService, MailchimpSegmentService, MailchimpCampaignService, MemberResourcesReferenceData, MailchimpConfig, Notifier, MemberResourcesService, CommitteeReferenceData, ModalService, SiteEditService) { var logger = $log.getInstance("HowToController"); $log.logLevels["HowToController"] = $log.LEVEL.OFF; $scope.notify = {}; var notify = Notifier($scope.notify); notify.setBusy(); $scope.fileUtils = FileUtils; $scope.memberResourcesReferenceData = MemberResourcesReferenceData; $scope.mailchimpLinkService = MailchimpLinkService; $scope.destinationType = ""; $scope.members = []; $scope.memberResources = []; $scope.alertMessages = []; $scope.allowConfirmDelete = false; $scope.selected = { addingNew: false, }; $scope.isActive = function (memberResource) { var active = SiteEditService.active() && LoggedInMemberService.memberLoggedIn() && memberResource === $scope.selected.memberResource; logger.debug("isActive =", active, "with memberResource", memberResource); return active; }; $scope.allowAdd = function () { return SiteEditService.active() && LoggedInMemberService.allowFileAdmin(); }; $scope.allowEdit = function (memberResource) { return $scope.allowAdd() && memberResource && memberResource.$id(); }; $scope.allowDelete = function (memberResource) { return $scope.allowEdit(memberResource); }; var defaultMemberResource = function () { return new MemberResourcesService({ data: {campaignSearchLimit: "1000", campaignSearchField: "title"}, resourceType: "email", accessLevel: "hidden", createdDate: DateUtils.nowAsValue(), createdBy: LoggedInMemberService.loggedInMember().memberId }) }; function removeDeleteOrAddOrInProgressFlags() { $scope.allowConfirmDelete = false; $scope.selected.addingNew = false; } $scope.delete = function () { $scope.allowConfirmDelete = true; }; $scope.cancelDelete = function () { removeDeleteOrAddOrInProgressFlags(); }; $scope.confirmDelete = function () { notify.setBusy(); function showDeleted() { return notify.success("member resource was deleted successfully"); } $scope.selected.memberResource.$remove(showDeleted, showDeleted, notify.error, notify.error) .then($scope.hideDialog) .then(refreshMemberResources) .then(removeDeleteOrAddOrInProgressFlags) .then(notify.clearBusy); }; $scope.selectMemberResource = function (memberResource) { logger.debug("selectMemberResource with memberResource", memberResource, "$scope.selected.addingNew", $scope.selected.addingNew); if (!$scope.selected.addingNew) { $scope.selected.memberResource = memberResource; } }; $scope.edit = function () { ModalService.showModal({ templateUrl: "partials/howTo/how-to-dialog.html", controller: "HowToDialogController", preClose: function (modal) { logger.debug("preClose event with modal", modal); modal.element.modal("hide"); }, inputs: { memberResource: $scope.selected.memberResource } }).then(function (modal) { logger.debug("modal event with modal", modal); modal.element.modal(); modal.close.then(function (result) { logger.debug("close event with result", result); }); }) }; $scope.add = function () { $scope.selected.addingNew = true; var memberResource = defaultMemberResource(); $scope.selected.memberResource = memberResource; logger.debug("add:", memberResource); $scope.edit(); }; $scope.hideDialog = function () { removeDeleteOrAddOrInProgressFlags(); }; $scope.$on("memberResourcesChanged", function () { refreshAll(); }); $scope.$on("memberResourcesChanged", function () { refreshAll(); }); $scope.$on("memberLoginComplete", function () { refreshAll(); }); $scope.$on("memberLogoutComplete", function () { refreshAll(); }); $scope.$on("editSite", function (event, data) { logger.debug("editSite:", data); refreshAll(); }); function refreshMemberResources() { MemberResourcesService.all() .then(function (memberResources) { if (URLService.hasRouteParameter("memberResourceId")) { $scope.memberResources = _.filter(memberResources, function (memberResource) { return memberResource.$id() === $routeParams.memberResourceId; }); } else { $scope.memberResources = _.chain(memberResources) .filter(function (memberResource) { return $scope.memberResourcesReferenceData.accessLevelFor(memberResource.accessLevel).filter(); }).sortBy("resourceDate") .value() .reverse(); logger.debug(memberResources.length, "memberResources", $scope.memberResources.length, "filtered memberResources"); } }); } function refreshAll() { refreshMemberResources(); } refreshAll(); }]); /* concatenated from client/src/app/js/httpServices.js */ angular.module('ekwgApp') .factory('HTTPResponseService', ["$log", function ($log) { var logger = $log.getInstance('HTTPResponseService'); $log.logLevels['HTTPResponseService'] = $log.LEVEL.OFF; function returnResponse(response) { logger.debug('response.data=', response.data); var returnObject = (typeof response.data === 'object') || !response.data ? response.data : JSON.parse(response.data); logger.debug('returned ', typeof response.data, 'response status =', response.status, returnObject.length, 'response items:', returnObject); return returnObject; } return { returnResponse: returnResponse } }]); /* concatenated from client/src/app/js/imageEditor.js */ angular.module('ekwgApp') .controller('ImageEditController', ["$scope", "$location", "Upload", "$http", "$q", "$routeParams", "$window", "LoggedInMemberService", "ContentMetaDataService", "Notifier", "EKWGFileUpload", function($scope, $location, Upload, $http, $q, $routeParams, $window, LoggedInMemberService, ContentMetaDataService, Notifier, EKWGFileUpload) { var notify = Notifier($scope); $scope.imageSource = $routeParams.imageSource; applyAllowEdits(); $scope.onFileSelect = function(file) { if (file) { $scope.uploadedFile = file; EKWGFileUpload.onFileSelect(file, notify, $scope.imageSource).then(function(fileNameData) { $scope.currentImageMetaDataItem.image = $scope.imageMetaData.baseUrl + '/' + fileNameData.awsFileName; console.log(' $scope.currentImageMetaDataItem.image', $scope.currentImageMetaDataItem.image); }); } }; $scope.refreshImageMetaData = function(imageSource) { notify.setBusy(); $scope.imageSource = imageSource; ContentMetaDataService.getMetaData(imageSource).then(function(contentMetaData) { $scope.imageMetaData = contentMetaData; notify.clearBusy(); }, function(response) { notify.error(response); }); }; $scope.refreshImageMetaData($scope.imageSource); $scope.$on('memberLoginComplete', function() { applyAllowEdits(); }); $scope.$on('memberLogoutComplete', function() { applyAllowEdits(); }); $scope.exitBackToPreviousWindow = function() { $window.history.back(); }; $scope.reverseSortOrder = function() { $scope.imageMetaData.files = $scope.imageMetaData.files.reverse(); }; $scope.imageTitleLength = function() { if ($scope.imageSource === 'imagesHome') { return 50; } else { return 20 } }; $scope.replace = function(imageMetaDataItem) { $scope.files = []; $scope.currentImageMetaDataItem = imageMetaDataItem; $('#hidden-input').click(); }; $scope.moveUp = function(imageMetaDataItem) { var currentIndex = $scope.imageMetaData.files.indexOf(imageMetaDataItem); if (currentIndex > 0) { $scope.delete(imageMetaDataItem); $scope.imageMetaData.files.splice(currentIndex - 1, 0, imageMetaDataItem); } }; $scope.moveDown = function(imageMetaDataItem) { var currentIndex = $scope.imageMetaData.files.indexOf(imageMetaDataItem); if (currentIndex < $scope.imageMetaData.files.length) { $scope.delete(imageMetaDataItem); $scope.imageMetaData.files.splice(currentIndex + 1, 0, imageMetaDataItem); } }; $scope.delete = function(imageMetaDataItem) { $scope.imageMetaData.files = _.without($scope.imageMetaData.files, imageMetaDataItem); }; $scope.insertHere = function(imageMetaDataItem) { var insertedImageMetaDataItem = new ContentMetaDataService.createNewMetaData(true); var currentIndex = $scope.imageMetaData.files.indexOf(imageMetaDataItem); $scope.imageMetaData.files.splice(currentIndex, 0, insertedImageMetaDataItem); $scope.replace(insertedImageMetaDataItem); }; $scope.currentImageMetaDataItemBeingUploaded = function(imageMetaDataItem) { return ($scope.currentImageMetaDataItem && $scope.currentImageMetaDataItem.$$hashKey === imageMetaDataItem.$$hashKey); }; $scope.saveAll = function() { ContentMetaDataService.saveMetaData($scope.imageMetaData, saveOrUpdateSuccessful, notify.error) .then(function(contentMetaData) { $scope.exitBackToPreviousWindow(); }, function(response) { notify.error(response); }); }; function applyAllowEdits() { $scope.allowEdits = LoggedInMemberService.allowContentEdits(); } function saveOrUpdateSuccessful() { notify.success('data for ' + $scope.imageMetaData.files.length + ' images was saved successfully.'); } }]); /* concatenated from client/src/app/js/indexController.js */ angular.module('ekwgApp') .controller("IndexController", ["$q", "$cookieStore", "$log", "$scope", "$rootScope", "URLService", "LoggedInMemberService", "ProfileConfirmationService", "AuthenticationModalsService", "Notifier", "DateUtils", function ($q, $cookieStore, $log, $scope, $rootScope, URLService, LoggedInMemberService, ProfileConfirmationService, AuthenticationModalsService, Notifier, DateUtils) { var logger = $log.getInstance("IndexController"); $log.logLevels["IndexController"] = $log.LEVEL.OFF; $scope.notify = {}; var notify = Notifier($scope.notify); logger.info('called IndexController'); $scope.ready = false; $scope.year = DateUtils.asString(DateUtils.momentNow().valueOf(), undefined, "YYYY"); $scope.actions = { forgotPassword: function () { URLService.navigateTo("forgot-password"); }, loginOrLogout: function () { if (LoggedInMemberService.memberLoggedIn()) { LoggedInMemberService.logout(); } else { URLService.navigateTo("login"); } } }; $scope.memberLoggedIn = function () { return LoggedInMemberService.memberLoggedIn() }; $scope.memberLoginStatus = function () { if (LoggedInMemberService.memberLoggedIn()) { var loggedInMember = LoggedInMemberService.loggedInMember(); return "Logout " + loggedInMember.firstName + " " + loggedInMember.lastName; } else { return "Login to EWKG Site"; } }; $scope.allowEdits = function () { return LoggedInMemberService.allowContentEdits(); }; $scope.isHome = function () { return URLService.relativeUrlFirstSegment() === "/"; }; $scope.isOnPage = function (data) { var matchedUrl = s.endsWith(URLService.relativeUrlFirstSegment(), data); logger.debug("isOnPage", matchedUrl, "data=", data); return matchedUrl; }; $scope.isProfileOrAdmin = function () { return $scope.isOnPage("profile") || $scope.isOnPage("admin"); }; }]); /* concatenated from client/src/app/js/instagramServices.js */ angular.module('ekwgApp') .factory('InstagramService', ["$http", "HTTPResponseService", function ($http, HTTPResponseService) { function recentMedia() { return $http.get('/instagram/recentMedia').then(HTTPResponseService.returnResponse); } return { recentMedia: recentMedia, } }]); /* concatenated from client/src/app/js/letterheadController.js */ angular.module('ekwgApp') .controller('LetterheadController', ["$scope", "$location", function ($scope, $location) { var pathParts = $location.path().replace('/letterhead/', '').split('/'); $scope.firstPart = _.first(pathParts); $scope.lastPart = _.last(pathParts); }]); /* concatenated from client/src/app/js/links.js */ angular.module('ekwgApp') .factory('ContactUsAmendService', ["$filter", "LoggedInMemberService", "DateUtils", function ($filter, LoggedInMemberService, DateUtils) { }]) .controller('ContactUsController', ["$log", "$rootScope", "$routeParams", "$scope", "CommitteeReferenceData", "LoggedInMemberService", function ($log, $rootScope, $routeParams, $scope, CommitteeReferenceData, LoggedInMemberService) { var logger = $log.getInstance('ContactUsController'); $log.logLevels['ContactUsController'] = $log.LEVEL.OFF; $scope.contactUs = { ready: function () { return CommitteeReferenceData.ready; } }; $scope.allowEdits = function () { return LoggedInMemberService.allowMemberAdminEdits(); } }]); /* concatenated from client/src/app/js/loggedInMemberService.js */ angular.module('ekwgApp') .factory('LoggedInMemberService', ["$rootScope", "$q", "$routeParams", "$cookieStore", "URLService", "MemberService", "MemberAuditService", "DateUtils", "NumberUtils", "$log", function ($rootScope, $q, $routeParams, $cookieStore, URLService, MemberService, MemberAuditService, DateUtils, NumberUtils, $log) { var logger = $log.getInstance('LoggedInMemberService'); var noLogger = $log.getInstance('NoLogger'); $log.logLevels['NoLogger'] = $log.LEVEL.OFF; $log.logLevels['LoggedInMemberService'] = $log.LEVEL.OFF; function loggedInMember() { if (!getCookie('loggedInMember')) setCookie('loggedInMember', {}); return getCookie('loggedInMember'); } function loginResponse() { if (!getCookie('loginResponse')) setCookie('loginResponse', {memberLoggedIn: false}); return getCookie('loginResponse'); } function showResetPassword() { return getCookie('showResetPassword'); } function allowContentEdits() { return memberLoggedIn() ? loggedInMember().contentAdmin : false; } function allowMemberAdminEdits() { return loginResponse().memberLoggedIn ? loggedInMember().memberAdmin : false; } function allowFinanceAdmin() { return loginResponse().memberLoggedIn ? loggedInMember().financeAdmin : false; } function allowCommittee() { return loginResponse().memberLoggedIn ? loggedInMember().committee : false; } function allowTreasuryAdmin() { return loginResponse().memberLoggedIn ? loggedInMember().treasuryAdmin : false; } function allowFileAdmin() { return loginResponse().memberLoggedIn ? loggedInMember().fileAdmin : false; } function memberLoggedIn() { return !_.isEmpty(loggedInMember()) && loginResponse().memberLoggedIn; } function showLoginPromptWithRouteParameter(routeParameter) { if (URLService.hasRouteParameter(routeParameter) && !memberLoggedIn()) $('#login-dialog').modal(); } function allowWalkAdminEdits() { return memberLoggedIn() ? loggedInMember().walkAdmin : false; } function allowSocialAdminEdits() { return memberLoggedIn() ? loggedInMember().socialAdmin : false; } function allowSocialDetailView() { return memberLoggedIn() ? loggedInMember().socialMember : false; } function logout() { var member = loggedInMember(); var loginResponseValue = loginResponse(); if (!_.isEmpty(member)) { loginResponseValue.alertMessage = 'The member ' + member.userName + ' logged out successfully'; auditMemberLogin(member.userName, undefined, member, loginResponseValue) } removeCookie('loginResponse'); removeCookie('loggedInMember'); removeCookie('showResetPassword'); removeCookie('editSite'); $rootScope.$broadcast('memberLogoutComplete'); } function auditMemberLogin(userName, password, member, loginResponse) { var audit = new MemberAuditService({ userName: userName, password: password, loginTime: DateUtils.nowAsValue(), loginResponse: loginResponse }); if (!_.isEmpty(member)) audit.member = member; return audit.$save(); } function setCookie(key, value) { noLogger.debug('setting cookie ' + key + ' with value ', value); $cookieStore.put(key, value); } function removeCookie(key) { logger.info('removing cookie ' + key); $cookieStore.remove(key); } function getCookie(key) { var object = $cookieStore.get(key); noLogger.debug('getting cookie ' + key + ' with value', object); return object; } function login(userName, password) { return getMemberForUserName(userName) .then(function (member) { removeCookie('showResetPassword'); var loginResponse = {}; if (!_.isEmpty(member)) { loginResponse.memberLoggedIn = false; if (!member.groupMember) { loginResponse.alertMessage = 'Logins for member ' + userName + ' have been disabled. Please'; } else if (member.password !== password) { loginResponse.alertMessage = 'The password was incorrectly entered for ' + userName + '. Please try again or'; } else if (member.expiredPassword) { setCookie('showResetPassword', true); loginResponse.alertMessage = 'The password for ' + userName + ' has expired. You must enter a new password before continuing. Alternatively'; } else { loginResponse.memberLoggedIn = true; loginResponse.alertMessage = 'The member ' + userName + ' logged in successfully'; setLoggedInMemberCookie(member); } } else { removeCookie('loggedInMember'); loginResponse.alertMessage = 'The member ' + userName + ' was not recognised. Please try again or'; } return {loginResponse: loginResponse, member: member}; }) .then(function (loginData) { setCookie('loginResponse', loginData.loginResponse); return auditMemberLogin(userName, password, loginData.member, loginData.loginResponse) .then(function () { logger.debug('loginResponse =', loginData.loginResponse); return $rootScope.$broadcast('memberLoginComplete'); } ); }, function (response) { throw new Error('Something went wrong...' + response); }) } function setLoggedInMemberCookie(member) { var memberId = member.$id(); var cookie = getCookie('loggedInMember'); if (_.isEmpty(cookie) || (cookie.memberId === memberId)) { var newCookie = angular.extend(member, {memberId: memberId}); logger.debug('saving loggedInMember ->', newCookie); setCookie('loggedInMember', newCookie); } else { logger.debug('not saving member (' + memberId + ') to cookie as not currently logged in member (' + cookie.memberId + ')', member); } } function saveMember(memberToSave, saveCallback, errorSaveCallback) { memberToSave.$saveOrUpdate(saveCallback, saveCallback, errorSaveCallback, errorSaveCallback) .then(function () { setLoggedInMemberCookie(memberToSave); }) .then(function () { $rootScope.$broadcast('memberSaveComplete'); }); } function resetPassword(userName, newPassword, newPasswordConfirm) { return getMemberForUserName(userName) .then(validateNewPassword) .then(saveSuccessfulPasswordReset) .then(broadcastMemberLoginComplete) .then(auditPasswordChange); function validateNewPassword(member) { var loginResponse = {memberLoggedIn: false}; var showResetPassword = true; if (member.password === newPassword) { loginResponse.alertMessage = 'The new password was the same as the old one for ' + member.userName + '. Please try again or'; } else if (!newPassword || newPassword.length < 6) { loginResponse.alertMessage = 'The new password needs to be at least 6 characters long. Please try again or'; } else if (newPassword !== newPasswordConfirm) { loginResponse.alertMessage = 'The new password was not confirmed correctly for ' + member.userName + '. Please try again or'; } else { showResetPassword = false; logger.debug('Saving new password for ' + member.userName + ' and removing expired status'); delete member.expiredPassword; delete member.passwordResetId; member.password = newPassword; loginResponse.memberLoggedIn = true; loginResponse.alertMessage = 'The password for ' + member.userName + ' was changed successfully'; } return {loginResponse: loginResponse, member: member, showResetPassword: showResetPassword}; } function saveSuccessfulPasswordReset(resetPasswordData) { logger.debug('saveNewPassword.resetPasswordData:', resetPasswordData); setCookie('loginResponse', resetPasswordData.loginResponse); setCookie('showResetPassword', resetPasswordData.showResetPassword); if (!resetPasswordData.showResetPassword) { return resetPasswordData.member.$update().then(function () { setLoggedInMemberCookie(resetPasswordData.member); return resetPasswordData; }) } else { return resetPasswordData; } } function auditPasswordChange(resetPasswordData) { return auditMemberLogin(userName, resetPasswordData.member.password, resetPasswordData.member, resetPasswordData.loginResponse) } function broadcastMemberLoginComplete(resetPasswordData) { $rootScope.$broadcast('memberLoginComplete'); return resetPasswordData } } function getMemberForUserName(userName) { return MemberService.query({userName: userName.toLowerCase()}, {limit: 1}) .then(function (queryResults) { return (queryResults && queryResults.length > 0) ? queryResults[0] : {}; }); } function getMemberForResetPassword(credentialOne, credentialTwo) { var credentialOneCleaned = credentialOne.toLowerCase().trim(); var credentialTwoCleaned = credentialTwo.toUpperCase().trim(); var orOne = {$or: [{userName: {$eq: credentialOneCleaned}}, {email: {$eq: credentialOneCleaned}}]}; var orTwo = {$or: [{membershipNumber: {$eq: credentialTwoCleaned}}, {postcode: {$eq: credentialTwoCleaned}}]}; var criteria = {$and: [orOne, orTwo]}; logger.info("querying member using", criteria); return MemberService.query(criteria, {limit: 1}) .then(function (queryResults) { logger.info("queryResults:", queryResults); return (queryResults && queryResults.length > 0) ? queryResults[0] : {}; }); } function getMemberForMemberId(memberId) { return MemberService.getById(memberId) } function getMemberByPasswordResetId(passwordResetId) { return MemberService.query({passwordResetId: passwordResetId}, {limit: 1}) .then(function (queryResults) { return (queryResults && queryResults.length > 0) ? queryResults[0] : {}; }); } function setPasswordResetId(member) { member.passwordResetId = NumberUtils.generateUid(); logger.debug('member.userName', member.userName, 'member.passwordResetId', member.passwordResetId); return member; } return { auditMemberLogin: auditMemberLogin, setPasswordResetId: setPasswordResetId, getMemberByPasswordResetId: getMemberByPasswordResetId, getMemberForResetPassword: getMemberForResetPassword, getMemberForUserName: getMemberForUserName, getMemberForMemberId: getMemberForMemberId, loggedInMember: loggedInMember, loginResponse: loginResponse, logout: logout, login: login, saveMember: saveMember, resetPassword: resetPassword, memberLoggedIn: memberLoggedIn, allowContentEdits: allowContentEdits, allowMemberAdminEdits: allowMemberAdminEdits, allowWalkAdminEdits: allowWalkAdminEdits, allowSocialAdminEdits: allowSocialAdminEdits, allowSocialDetailView: allowSocialDetailView, allowCommittee: allowCommittee, allowFinanceAdmin: allowFinanceAdmin, allowTreasuryAdmin: allowTreasuryAdmin, allowFileAdmin: allowFileAdmin, showResetPassword: showResetPassword, showLoginPromptWithRouteParameter: showLoginPromptWithRouteParameter }; }] ); /* concatenated from client/src/app/js/loginController.js */ angular.module('ekwgApp') .controller('LoginController', ["$log", "$scope", "$routeParams", "LoggedInMemberService", "AuthenticationModalsService", "Notifier", "URLService", "ValidationUtils", "close", function ($log, $scope, $routeParams, LoggedInMemberService, AuthenticationModalsService, Notifier, URLService, ValidationUtils, close) { $scope.notify = {}; var logger = $log.getInstance('LoginController'); $log.logLevels['LoginController'] = $log.LEVEL.OFF; var notify = Notifier($scope.notify); LoggedInMemberService.logout(); $scope.actions = { submittable: function () { var userNamePopulated = ValidationUtils.fieldPopulated($scope.enteredMemberCredentials, "userName"); var passwordPopulated = ValidationUtils.fieldPopulated($scope.enteredMemberCredentials, "password"); logger.info("submittable: userNamePopulated", userNamePopulated, "passwordPopulated", passwordPopulated); return passwordPopulated && userNamePopulated; }, forgotPassword: function () { URLService.navigateTo("forgot-password"); }, close: function () { close() }, login: function () { notify.showContactUs(false); notify.setBusy(); notify.progress({ busy: true, title: "Logging in", message: "using credentials for " + $scope.enteredMemberCredentials.userName + " - please wait" }); LoggedInMemberService.login($scope.enteredMemberCredentials.userName, $scope.enteredMemberCredentials.password).then(function () { var loginResponse = LoggedInMemberService.loginResponse(); if (LoggedInMemberService.memberLoggedIn()) { close(); if (!LoggedInMemberService.loggedInMember().profileSettingsConfirmed) { return URLService.navigateTo("mailing-preferences"); } return true; } else if (LoggedInMemberService.showResetPassword()) { return AuthenticationModalsService.showResetPasswordModal($scope.enteredMemberCredentials.userName, "Your password has expired, therefore you need to reset it to a new one before continuing."); } else { notify.showContactUs(true); notify.error({ title: "Login failed", message: loginResponse.alertMessage }); } }); }, } }] ); /* concatenated from client/src/app/js/mailChimpServices.js */ angular.module('ekwgApp') .factory('MailchimpConfig', ["Config", function (Config) { function getConfig() { return Config.getConfig('mailchimp', { mailchimp: { interestGroups: { walks: {interestGroupingId: undefined}, socialEvents: {interestGroupingId: undefined}, general: {interestGroupingId: undefined} }, segments: { walks: {segmentId: undefined}, socialEvents: {segmentId: undefined}, general: { passwordResetSegmentId: undefined, forgottenPasswordSegmentId: undefined, committeeSegmentId: undefined } } } }) } function saveConfig(config, key, saveCallback, errorSaveCallback) { return Config.saveConfig('mailchimp', config, key, saveCallback, errorSaveCallback); } return { getConfig: getConfig, saveConfig: saveConfig } }]) .factory('MailchimpHttpService', ["$log", "$q", "$http", "MailchimpErrorParserService", function ($log, $q, $http, MailchimpErrorParserService) { var logger = $log.getInstance('MailchimpHttpService'); $log.logLevels['MailchimpHttpService'] = $log.LEVEL.OFF; function call(serviceCallType, method, url, data, params) { var deferredTask = $q.defer(); deferredTask.notify(serviceCallType); logger.debug(serviceCallType); $http({ method: method, data: data, params: params, url: url }).then(function (response) { var responseData = response.data; var errorObject = MailchimpErrorParserService.extractError(responseData); if (errorObject.error) { var errorResponse = {message: serviceCallType + ' was not successful', error: errorObject.error}; logger.debug(errorResponse); deferredTask.reject(errorResponse); } else { logger.debug('success', responseData); deferredTask.resolve(responseData); return responseData; } }).catch(function (response) { var responseData = response.data; var errorObject = MailchimpErrorParserService.extractError(responseData); var errorResponse = {message: serviceCallType + ' was not successful', error: errorObject.error}; logger.debug(errorResponse); deferredTask.reject(errorResponse); }); return deferredTask.promise; } return { call: call } }]) .factory('MailchimpErrorParserService', ["$log", function ($log) { var logger = $log.getInstance('MailchimpErrorParserService'); $log.logLevels['MailchimpErrorParserService'] = $log.LEVEL.OFF; function extractError(responseData) { var error; if (responseData && (responseData.error || responseData.errno)) { error = {error: responseData} } else if (responseData && responseData.errors && responseData.errors.length > 0) { error = { error: _.map(responseData.errors, function (error) { var response = error.error; if (error.email && error.email.email) { response += (': ' + error.email.email); } return response; }).join(', ') } } else { error = {error: undefined} } logger.debug('responseData:', responseData, 'error:', error) return error; } return { extractError: extractError } }]) .factory('MailchimpLinkService', ["$log", "MAILCHIMP_APP_CONSTANTS", function ($log, MAILCHIMP_APP_CONSTANTS) { var logger = $log.getInstance('MailchimpLinkService'); $log.logLevels['MailchimpLinkService'] = $log.LEVEL.OFF; function campaignPreview(webId) { return MAILCHIMP_APP_CONSTANTS.apiServer + "/campaigns/preview-content-html?id=" + webId; } function campaignEdit(webId) { return MAILCHIMP_APP_CONSTANTS.apiServer + "/campaigns/preview-content-html?id=" + webId; } return { campaignPreview: campaignPreview } }]) .factory('MailchimpGroupService', ["$log", "$rootScope", "$q", "$filter", "DateUtils", "MailchimpConfig", "MailchimpHttpService", function ($log, $rootScope, $q, $filter, DateUtils, MailchimpConfig, MailchimpHttpService) { var logger = $log.getInstance('MailchimpGroupService'); $log.logLevels['MailchimpGroupService'] = $log.LEVEL.OFF; var addInterestGroup = function (listType, interestGroupName, interestGroupingId) { return MailchimpHttpService.call('Adding Mailchimp Interest Group for ' + listType, 'POST', 'mailchimp/lists/' + listType + '/interestGroupAdd', { interestGroupingId: interestGroupingId, interestGroupName: interestGroupName }); }; var deleteInterestGroup = function (listType, interestGroupName, interestGroupingId) { return MailchimpHttpService.call('Deleting Mailchimp Interest Group for ' + listType, 'DELETE', 'mailchimp/lists/' + listType + '/interestGroupDel', { interestGroupingId: interestGroupingId, interestGroupName: interestGroupName }); }; var addInterestGrouping = function (listType, interestGroupingName, groups) { return MailchimpHttpService.call('Adding Mailchimp Interest Grouping for ' + listType, 'POST', 'mailchimp/lists/' + listType + '/interestGroupingAdd', { groups: groups, interestGroupingName: interestGroupingName }); }; var deleteInterestGrouping = function (listType, interestGroupingId) { return MailchimpHttpService.call('Deleting Mailchimp Interest Grouping for ' + listType, 'DELETE', 'mailchimp/lists/' + listType + '/interestGroupingDel', {interestGroupingId: interestGroupingId}); }; var listInterestGroupings = function (listType) { return MailchimpHttpService.call('Listing Mailchimp Interest Groupings for ' + listType, 'GET', 'mailchimp/lists/' + listType + '/interestGroupings'); }; var updateInterestGrouping = function (listType, interestGroupingId, interestGroupingName, interestGroupingValue) { return MailchimpHttpService.call('Updating Mailchimp Interest Groupings for ' + listType, 'PUT', 'mailchimp/lists/' + listType + '/interestGroupingUpdate', { interestGroupingId: interestGroupingId, interestGroupingName: interestGroupingName, interestGroupingValue: interestGroupingValue }); }; var updateInterestGroup = function (listType, oldName, newName) { return function (config) { var interestGroupingId = config.mailchimp.interestGroups[listType].interestGroupingId; return MailchimpHttpService.call('Updating Mailchimp Interest Group for ' + listType, 'PUT', 'mailchimp/lists/' + listType + '/interestGroupUpdate', { interestGroupingId: interestGroupingId, oldName: oldName, newName: newName }) .then(returnInterestGroupingId(interestGroupingId)); } }; var saveInterestGroup = function (listType, oldName, newName) { oldName = oldName.substring(0, 60); newName = newName.substring(0, 60); return MailchimpConfig.getConfig() .then(updateInterestGroup(listType, oldName, newName)) .then(findInterestGroup(listType, newName)); }; var createInterestGroup = function (listType, interestGroupName) { return MailchimpConfig.getConfig() .then(createOrUpdateInterestGroup(listType, interestGroupName)) .then(findInterestGroup(listType, interestGroupName)); }; var createOrUpdateInterestGroup = function (listType, interestGroupName) { return function (config) { logger.debug('createOrUpdateInterestGroup using config', config); var interestGroupingName = s.titleize(s.humanize(listType)); var interestGroupingId = config.mailchimp.interestGroups[listType].interestGroupingId; if (interestGroupingId) { return addInterestGroup(listType, interestGroupName, interestGroupingId) .then(returnInterestGroupingId(interestGroupingId)); } else { return addInterestGrouping(listType, interestGroupingName + ' Interest Groups', [interestGroupName]) .then(saveInterestGroupConfigAndReturnInterestGroupingId(listType, config)); } } }; var returnInterestGroupingId = function (interestGroupingId) { return function (response) { logger.debug('received', response, 'returning', interestGroupingId); return interestGroupingId; } }; var saveInterestGroupConfigAndReturnInterestGroupingId = function (listType, config) { return function (response) { config.mailchimp.interestGroups[listType].interestGroupingId = response.id; logger.debug('saving config', config); return MailchimpConfig.saveConfig(config, function () { logger.debug('config save was successful'); return response.id; }, function (error) { throw Error('config save was not successful. ' + error) }); } }; var findInterestGroup = function (listType, interestGroupName) { return function (interestGroupingId) { logger.debug('finding findInterestGroup ', interestGroupingId); return listInterestGroupings(listType) .then(filterInterestGroupings(interestGroupingId, interestGroupName)); } }; var filterInterestGroupings = function (interestGroupingId, interestGroupName) { return function (interestGroupings) { logger.debug('filterInterestGroupings: interestGroupings passed in ', interestGroupings, 'for interestGroupingId', interestGroupingId); var interestGrouping = _.find(interestGroupings, function (interestGrouping) { return interestGrouping.id === interestGroupingId; }); logger.debug('filterInterestGroupings: interestGrouping returned ', interestGrouping); var interestGroup = _.find(interestGrouping.groups, function (group) { return group.name === interestGroupName; }); logger.debug('filterInterestGroupings: interestGroup returned', interestGroup); return interestGroup; } }; return { createInterestGroup: createInterestGroup, saveInterestGroup: saveInterestGroup } }]) .factory('MailchimpSegmentService', ["$log", "$rootScope", "$q", "$filter", "DateUtils", "MailchimpConfig", "MailchimpHttpService", "EmailSubscriptionService", "MemberService", "StringUtils", function ($log, $rootScope, $q, $filter, DateUtils, MailchimpConfig, MailchimpHttpService, EmailSubscriptionService, MemberService, StringUtils) { var logger = $log.getInstance('MailchimpSegmentService'); $log.logLevels['MailchimpSegmentService'] = $log.LEVEL.OFF; function addSegment(listType, segmentName) { return MailchimpHttpService.call('Adding Mailchimp segment for ' + listType, 'POST', 'mailchimp/lists/' + listType + '/segmentAdd', {segmentName: segmentName}); } function resetSegment(listType, segmentId) { return MailchimpHttpService.call('Resetting Mailchimp segment for ' + listType, 'PUT', 'mailchimp/lists/' + listType + '/segmentReset', {segmentId: segmentId}); } function deleteSegment(listType, segmentId) { return MailchimpHttpService.call('Deleting Mailchimp segment for ' + listType, 'DELETE', 'mailchimp/lists/' + listType + '/segmentDel/' + segmentId); } function callRenameSegment(listType, segmentId, segmentName) { return function () { return renameSegment(listType, segmentId, segmentName); } } function renameSegment(listType, segmentId, segmentNameInput) { var segmentName = StringUtils.stripLineBreaks(StringUtils.left(segmentNameInput, 99), true); logger.debug('renaming segment with name=\'' + segmentName + '\' length=' + segmentName.length); return MailchimpHttpService.call('Renaming Mailchimp segment for ' + listType, 'POST', 'mailchimp/lists/' + listType + '/segmentRename', { segmentId: segmentId, segmentName: segmentName }); } function callAddSegmentMembers(listType, segmentId, segmentMembers) { return function () { return addSegmentMembers(listType, segmentId, segmentMembers); } } function addSegmentMembers(listType, segmentId, segmentMembers) { return MailchimpHttpService.call('Adding Mailchimp segment members ' + JSON.stringify(segmentMembers) + ' for ' + listType, 'POST', 'mailchimp/lists/' + listType + '/segmentMembersAdd', { segmentId: segmentId, segmentMembers: segmentMembers }); } function callDeleteSegmentMembers(listType, segmentId, segmentMembers) { return function () { return deleteSegmentMembers(listType, segmentId, segmentMembers); } } function deleteSegmentMembers(listType, segmentId, segmentMembers) { return MailchimpHttpService.call('Deleting Mailchimp segment members ' + segmentMembers + ' for ' + listType, 'DELETE', 'mailchimp/lists/' + listType + '/segmentMembersDel', { segmentId: segmentId, segmentMembers: segmentMembers }); } function listSegments(listType) { return MailchimpHttpService.call('Listing Mailchimp segments for ' + listType, 'GET', 'mailchimp/lists/' + listType + '/segments'); } function buildSegmentMemberData(listType, memberIds, members) { var segmentMembers = _.chain(memberIds) .map(function (memberId) { return MemberService.toMember(memberId, members) }) .filter(function (member) { return member && member.email; }) .map(function (member) { return EmailSubscriptionService.addMailchimpIdentifiersToRequest(member, listType); }) .value(); if (!segmentMembers || segmentMembers.length === 0) throw new Error('No members were added to the ' + listType + ' email segment from the ' + memberIds.length + ' supplied members. Please check that they have a valid email address and are subscribed to ' + listType); return segmentMembers; } function saveSegment(listType, mailchimpConfig, memberIds, segmentName, members) { var segmentMembers = buildSegmentMemberData(listType, memberIds, members); logger.debug('saveSegment:buildSegmentMemberData:', listType, memberIds, segmentMembers); if (mailchimpConfig && mailchimpConfig.segmentId) { var segmentId = mailchimpConfig.segmentId; logger.debug('saveSegment:segmentId', mailchimpConfig); return resetSegment(listType, segmentId) .then(callRenameSegment(listType, segmentId, segmentName)) .then(addSegmentMembersDuringUpdate(listType, segmentId, segmentMembers)) .then(returnAddSegmentResponse({id: segmentId})); } else { return addSegment(listType, segmentName) .then(addSegmentMembersDuringAdd(listType, segmentMembers)) } } function returnAddSegmentResponse(addSegmentResponse) { return function (addSegmentMembersResponse) { return {members: addSegmentMembersResponse.members, segment: addSegmentResponse}; }; } function returnAddSegmentAndMemberResponse(addSegmentResponse) { return function (addMemberResponse) { return ({segment: addSegmentResponse, members: addMemberResponse}); }; } function addSegmentMembersDuringUpdate(listType, segmentId, segmentMembers) { return function (renameSegmentResponse) { if (segmentMembers.length > 0) { return addSegmentMembers(listType, segmentId, segmentMembers) .then(returnAddSegmentAndMemberResponse(renameSegmentResponse)); } else { return {segment: renameSegmentResponse.id, members: {}}; } } } function addSegmentMembersDuringAdd(listType, segmentMembers) { return function (addSegmentResponse) { if (segmentMembers.length > 0) { return addSegmentMembers(listType, addSegmentResponse.id, segmentMembers) .then(returnAddSegmentAndMemberResponse(addSegmentResponse)); } else { return {segment: addSegmentResponse, members: {}}; } } } function getMemberSegmentId(member, segmentType) { if (member.mailchimpSegmentIds) return member.mailchimpSegmentIds[segmentType]; } function setMemberSegmentId(member, segmentType, segmentId) { if (!member.mailchimpSegmentIds) member.mailchimpSegmentIds = {}; member.mailchimpSegmentIds[segmentType] = segmentId; } function formatSegmentName(prefix) { var date = ' (' + DateUtils.nowAsValue() + ')'; var segmentName = prefix.substring(0, 99 - date.length) + date; logger.debug('segmentName', segmentName, 'length', segmentName.length); return segmentName; } return { formatSegmentName: formatSegmentName, saveSegment: saveSegment, deleteSegment: deleteSegment, getMemberSegmentId: getMemberSegmentId, setMemberSegmentId: setMemberSegmentId } }]) .factory('MailchimpListService', ["$log", "$rootScope", "$q", "$filter", "DateUtils", "MailchimpConfig", "MailchimpHttpService", "EmailSubscriptionService", "MemberService", function ($log, $rootScope, $q, $filter, DateUtils, MailchimpConfig, MailchimpHttpService, EmailSubscriptionService, MemberService) { var logger = $log.getInstance('MailchimpListService'); $log.logLevels['MailchimpListService'] = $log.LEVEL.OFF; var listSubscribers = function (listType) { return MailchimpHttpService.call('Listing Mailchimp subscribers for ' + listType, 'GET', 'mailchimp/lists/' + listType); }; var batchUnsubscribe = function (listType, subscribers) { return MailchimpHttpService.call('Batch unsubscribing members from Mailchimp List for ' + listType, 'POST', 'mailchimp/lists/' + listType + '/batchUnsubscribe', subscribers); }; var batchUnsubscribeMembers = function (listType, allMembers, notificationCallback) { return listSubscribers(listType) .then(filterSubscriberResponsesForUnsubscriptions(listType, allMembers)) .then(batchUnsubscribeForListType(listType, allMembers, notificationCallback)) .then(returnUpdatedMembers); }; function returnUpdatedMembers() { return MemberService.all(); } function batchUnsubscribeForListType(listType, allMembers, notificationCallback) { return function (subscribers) { if (subscribers.length > 0) { return batchUnsubscribe(listType, subscribers) .then(removeSubscriberDetailsFromMembers(listType, allMembers, subscribers, notificationCallback)); } else { notificationCallback('No members needed to be unsubscribed from ' + listType + ' list'); } } } function removeSubscriberDetailsFromMembers(listType, allMembers, subscribers, notificationCallback) { return function () { var updatedMembers = _.chain(subscribers) .map(function (subscriber) { var member = EmailSubscriptionService.responseToMember(listType, allMembers, subscriber); if (member) { member.mailchimpLists[listType] = {subscribed: false, updated: true}; member.$saveOrUpdate(); } else { notificationCallback('Could not find member from ' + listType + ' response containing data ' + JSON.stringify(subscriber)); } return member; }) .filter(function (member) { return member; }) .value(); $q.all(updatedMembers).then(function () { notificationCallback('Successfully unsubscribed ' + updatedMembers.length + ' member(s) from ' + listType + ' list'); return updatedMembers; }) } } function filterSubscriberResponsesForUnsubscriptions(listType, allMembers) { return function (listResponse) { return _.chain(listResponse.data) .filter(function (subscriber) { return EmailSubscriptionService.includeSubscriberInUnsubscription(listType, allMembers, subscriber); }) .map(function (subscriber) { return { email: subscriber.email, euid: subscriber.euid, leid: subscriber.leid }; }) .value(); } } return { batchUnsubscribeMembers: batchUnsubscribeMembers } }]) .factory('MailchimpCampaignService', ["MAILCHIMP_APP_CONSTANTS", "$log", "$rootScope", "$q", "$filter", "DateUtils", "MailchimpConfig", "MailchimpHttpService", function (MAILCHIMP_APP_CONSTANTS, $log, $rootScope, $q, $filter, DateUtils, MailchimpConfig, MailchimpHttpService) { var logger = $log.getInstance('MailchimpCampaignService'); $log.logLevels['MailchimpCampaignService'] = $log.LEVEL.OFF; function addCampaign(campaignId, campaignName) { return MailchimpHttpService.call('Adding Mailchimp campaign ' + campaignId + ' with name ' + campaignName, 'POST', 'mailchimp/campaigns/' + campaignId + '/campaignAdd', {campaignName: campaignName}); } function deleteCampaign(campaignId) { return MailchimpHttpService.call('Deleting Mailchimp campaign ' + campaignId, 'DELETE', 'mailchimp/campaigns/' + campaignId + '/delete'); } function getContent(campaignId) { return MailchimpHttpService.call('Getting Mailchimp content for campaign ' + campaignId, 'GET', 'mailchimp/campaigns/' + campaignId + '/content'); } function list(options) { return MailchimpHttpService.call('Listing Mailchimp campaigns', 'GET', 'mailchimp/campaigns/list', {}, options); } function setContent(campaignId, contentSections) { return contentSections ? MailchimpHttpService.call('Setting Mailchimp content for campaign ' + campaignId, 'POST', 'mailchimp/campaigns/' + campaignId + '/update', { updates: { name: "content", value: contentSections } }) : $q.when({ result: "success", campaignId: campaignId, message: "setContent skipped as no content provided" }) } function setOrClearSegment(replicatedCampaignId, optionalSegmentId) { if (optionalSegmentId) { return setSegmentId(replicatedCampaignId, optionalSegmentId); } else { return clearSegment(replicatedCampaignId) } } function setSegmentId(campaignId, segmentId) { return setSegmentOpts(campaignId, {saved_segment_id: segmentId}); } function clearSegment(campaignId) { return setSegmentOpts(campaignId, []); } function setSegmentOpts(campaignId, value) { return MailchimpHttpService.call('Setting Mailchimp segment opts for campaign ' + campaignId + ' with value ' + JSON.stringify(value), 'POST', 'mailchimp/campaigns/' + campaignId + '/update', { updates: { name: "segment_opts", value: value } }); } function setCampaignOptions(campaignId, campaignName, otherOptions) { var value = angular.extend({}, { title: campaignName.substring(0, 99), subject: campaignName }, otherOptions); return MailchimpHttpService.call('Setting Mailchimp campaign options for id ' + campaignId + ' with ' + JSON.stringify(value), 'POST', 'mailchimp/campaigns/' + campaignId + '/update', { updates: { name: "options", value: value } }); } function replicateCampaign(campaignId) { return MailchimpHttpService.call('Replicating Mailchimp campaign ' + campaignId, 'POST', 'mailchimp/campaigns/' + campaignId + '/replicate'); } function sendCampaign(campaignId) { if (!MAILCHIMP_APP_CONSTANTS.allowSendCampaign) throw new Error('You cannot send campaign ' + campaignId + ' as sending has been disabled'); return MailchimpHttpService.call('Sending Mailchimp campaign ' + campaignId, 'POST', 'mailchimp/campaigns/' + campaignId + '/send'); } function listCampaigns() { return MailchimpHttpService.call('Listing Mailchimp campaigns', 'GET', 'mailchimp/campaigns/list'); } function replicateAndSendWithOptions(options) { logger.debug('replicateAndSendWithOptions:options', options); return replicateCampaign(options.campaignId) .then(function (replicateCampaignResponse) { logger.debug('replicateCampaignResponse', replicateCampaignResponse); var replicatedCampaignId = replicateCampaignResponse.id; return setCampaignOptions(replicatedCampaignId, options.campaignName, options.otherSegmentOptions) .then(function (renameResponse) { logger.debug('renameResponse', renameResponse); return setContent(replicatedCampaignId, options.contentSections) .then(function (setContentResponse) { logger.debug('setContentResponse', setContentResponse); return setOrClearSegment(replicatedCampaignId, options.segmentId) .then(function (setSegmentResponse) { logger.debug('setSegmentResponse', setSegmentResponse); return options.dontSend ? replicateCampaignResponse : sendCampaign(replicatedCampaignId) }) }) }) }); } return { replicateAndSendWithOptions: replicateAndSendWithOptions, list: list } }]); /* concatenated from client/src/app/js/mailingPreferencesController.js */ angular.module('ekwgApp') .controller('MailingPreferencesController', ["$log", "$scope", "ProfileConfirmationService", "Notifier", "URLService", "LoggedInMemberService", "memberId", "close", function ($log, $scope, ProfileConfirmationService, Notifier, URLService, LoggedInMemberService, memberId, close) { var logger = $log.getInstance("MailingPreferencesController"); $log.logLevels["MailingPreferencesController"] = $log.LEVEL.OFF; $scope.notify = {}; var notify = Notifier($scope.notify); LoggedInMemberService.getMemberForMemberId(memberId) .then(function (member) { logger.info('memberId ->', memberId, 'member ->', member); $scope.member = member; }); function saveOrUpdateUnsuccessful(message) { notify.showContactUs(true); notify.error({ continue: true, title: "Error in saving mailing preferences", message: "Changes to your mailing preferences could not be saved. " + (message || "Please try again later.") }); } $scope.actions = { save: function () { ProfileConfirmationService.confirmProfile($scope.member); LoggedInMemberService.saveMember($scope.member, $scope.actions.close, saveOrUpdateUnsuccessful); }, close: function () { close(); } }; }]); /* concatenated from client/src/app/js/markdownEditor.js */ angular.module('ekwgApp') .component('markdownEditor', { templateUrl: 'partials/components/markdown-editor.html', controller: ["$cookieStore", "$log", "$rootScope", "$scope", "$element", "$attrs", "ContentText", function ($cookieStore, $log, $rootScope, $scope, $element, $attrs, ContentText) { var logger = $log.getInstance('MarkdownEditorController'); $log.logLevels['MarkdownEditorController'] = $log.LEVEL.OFF; var ctrl = this; ctrl.userEdits = {preview: true, saveInProgress: false, revertInProgress: false}; function assignData(data) { ctrl.data = data; ctrl.originalData = _.clone(data); logger.debug(ctrl.name, 'content retrieved:', data); return data; } function populateContent(type) { if (type) ctrl.userEdits[type + 'InProgress'] = true; return ContentText.forName(ctrl.name).then(function (data) { data = assignData(data); if (type) ctrl.userEdits[type + 'InProgress'] = false; return data; }); } ctrl.edit = function () { ctrl.userEdits.preview = false; }; ctrl.revert = function () { logger.debug('reverting ' + ctrl.name, 'content'); ctrl.data = _.clone(ctrl.originalData); }; ctrl.dirty = function () { var dirty = ctrl.data && ctrl.originalData && (ctrl.data.text !== ctrl.originalData.text); logger.debug(ctrl.name, 'dirty ->', dirty); return dirty; }; ctrl.revertGlyph = function () { return ctrl.userEdits.revertInProgress ? "fa fa-spinner fa-spin" : "glyphicon glyphicon-remove markdown-preview-icon" }; ctrl.saveGlyph = function () { return ctrl.userEdits.saveInProgress ? "fa fa-spinner fa-spin" : "glyphicon glyphicon-ok markdown-preview-icon" }; ctrl.save = function () { ctrl.userEdits.saveInProgress = true; logger.info('saving', ctrl.name, 'content', ctrl.data, $element, $attrs); ctrl.data.$saveOrUpdate().then(function (data) { ctrl.userEdits.saveInProgress = false; assignData(data); }) }; ctrl.editSite = function () { return $cookieStore.get('editSite'); }; ctrl.rows = function () { var text = _.property(["data", "text"])(ctrl); var rows = text ? text.split(/\r*\n/).length + 1 : 1; logger.info('number of rows in text ', text, '->', rows); return rows; }; ctrl.preview = function () { logger.info('previewing ' + ctrl.name, 'content', $element, $attrs); ctrl.userEdits.preview = true; }; ctrl.$onInit = function () { logger.debug('initialising:', ctrl.name, 'content, editSite:', ctrl.editSite()); if (!ctrl.description) { ctrl.description = ctrl.name; } populateContent(); }; }], bindings: { name: '@', description: '@', } }); /* concatenated from client/src/app/js/meetupServices.js */ angular.module('ekwgApp') .factory('MeetupService', ["$log", "$http", "HTTPResponseService", function ($log, $http, HTTPResponseService) { var logger = $log.getInstance('MeetupService'); $log.logLevels['MeetupService'] = $log.LEVEL.OFF; return { config: function () { return $http.get('/meetup/config').then(HTTPResponseService.returnResponse); }, eventUrlFor: function (meetupEventUrl) { return $http.get('/meetup/config').then(HTTPResponseService.returnResponse).then(function (meetupConfig) { return meetupConfig.url + '/' + meetupConfig.group + '/events/' + meetupEventUrl; }); }, eventsForStatus: function (status) { var queriedStatus = status || 'upcoming'; return $http({ method: 'get', params: { status: queriedStatus, }, url: '/meetup/events' }).then(function (response) { var returnValue = HTTPResponseService.returnResponse(response); logger.debug('eventsForStatus', queriedStatus, returnValue); return returnValue; }) } } }]); /* concatenated from client/src/app/js/memberAdmin.js */ angular.module('ekwgApp') .controller('MemberAdminController', ["$timeout", "$location", "$window", "$log", "$q", "$rootScope", "$routeParams", "$scope", "ModalService", "Upload", "StringUtils", "DbUtils", "URLService", "LoggedInMemberService", "MemberService", "MemberAuditService", "MemberBulkLoadAuditService", "MemberUpdateAuditService", "ProfileConfirmationService", "EmailSubscriptionService", "DateUtils", "MailchimpConfig", "MailchimpSegmentService", "MemberNamingService", "MailchimpCampaignService", "MailchimpListService", "Notifier", "ErrorMessageService", "MemberBulkUploadService", "ContentMetaDataService", "MONGOLAB_CONFIG", "MAILCHIMP_APP_CONSTANTS", function ($timeout, $location, $window, $log, $q, $rootScope, $routeParams, $scope, ModalService, Upload, StringUtils, DbUtils, URLService, LoggedInMemberService, MemberService, MemberAuditService, MemberBulkLoadAuditService, MemberUpdateAuditService, ProfileConfirmationService, EmailSubscriptionService, DateUtils, MailchimpConfig, MailchimpSegmentService, MemberNamingService, MailchimpCampaignService, MailchimpListService, Notifier, ErrorMessageService, MemberBulkUploadService, ContentMetaDataService, MONGOLAB_CONFIG, MAILCHIMP_APP_CONSTANTS) { var logger = $log.getInstance('MemberAdminController'); var noLogger = $log.getInstance('MemberAdminControllerNoLogger'); $log.logLevels['MemberAdminController'] = $log.LEVEL.OFF; $log.logLevels['MemberAdminControllerNoLogger'] = $log.LEVEL.OFF; $scope.memberAdminBaseUrl = ContentMetaDataService.baseUrl('memberAdmin'); $scope.notify = {}; var notify = Notifier($scope.notify); notify.setBusy(); var DESCENDING = '▼'; var ASCENDING = '▲'; $scope.today = DateUtils.momentNowNoTime().valueOf(); $scope.currentMember = {}; $scope.display = { saveInProgress: false }; $scope.calculateMemberFilterDate = function () { $scope.display.memberFilterDate = DateUtils.momentNowNoTime().subtract($scope.display && $scope.display.emailType.monthsInPast, 'months').valueOf(); }; $scope.showArea = function (area) { URLService.navigateTo('admin', area) }; $scope.display.emailTypes = [$scope.display.emailType]; $scope.dropSupported = true; $scope.memberAdminOpen = !URLService.hasRouteParameter('expenseId') && (URLService.isArea('member-admin') || URLService.noArea()); $scope.memberBulkLoadOpen = URLService.isArea('member-bulk-load'); $scope.memberAuditOpen = URLService.isArea('member-audit'); LoggedInMemberService.showLoginPromptWithRouteParameter('expenseId'); if (LoggedInMemberService.memberLoggedIn()) { refreshMembers() .then(refreshMemberAudit) .then(refreshMemberBulkLoadAudit) .then(refreshMemberUpdateAudit) .then(notify.clearBusy); } else { notify.clearBusy(); } $scope.currentMemberBulkLoadDisplayDate = function () { return DateUtils.currentMemberBulkLoadDisplayDate(); }; $scope.viewMailchimpListEntry = function (item) { $window.open(MAILCHIMP_APP_CONSTANTS.apiServer + "/lists/members/view?id=" + item, '_blank'); }; $scope.showSendEmailsDialog = function () { $scope.alertTypeResetPassword = false; $scope.display.emailMembers = []; ModalService.showModal({ templateUrl: "partials/admin/send-emails-dialog.html", controller: "MemberAdminSendEmailsController", preClose: function (modal) { logger.debug('preClose event with modal', modal); modal.element.modal('hide'); }, inputs: { members: $scope.members } }).then(function (modal) { logger.debug('modal event with modal', modal); modal.element.modal(); modal.close.then(function (result) { logger.debug('close event with result', result); }); }) }; function handleSaveError(errorResponse) { $scope.display.saveInProgress = false; applyAllowEdits(); var message = ErrorMessageService.stringify(errorResponse); var duplicate = s.include(message, 'duplicate'); logger.debug('errorResponse', errorResponse, 'duplicate', duplicate); if (duplicate) { message = 'Duplicate data was detected. A member record must have a unique Email Address, Display Name, Ramblers Membership Number and combination of First Name, Last Name and Alias. Please amend the current member and try again.'; $scope.display.duplicate = true; } notify.clearBusy(); notify.error({ title: 'Member could not be saved', message: message }); } function resetSendFlags() { logger.debug('resetSendFlags'); $scope.display.saveInProgress = false; return applyAllowEdits(); } $scope.showPasswordResetAlert = function () { return $scope.notify.showAlert && $scope.alertTypeResetPassword; }; $scope.uploadSessionStatuses = [ {title: "All"}, {status: "created", title: "Created"}, {status: "summary", title: "Summary"}, {status: "skipped", title: "Skipped"}, {status: "updated", title: "Updated"}, {status: "error", title: "Error"}]; $scope.filters = { uploadSession: {selected: undefined}, memberUpdateAudit: { query: $scope.uploadSessionStatuses[0], orderByField: 'updateTime', reverseSort: true, sortDirection: DESCENDING }, membersUploaded: { query: '', orderByField: 'email', reverseSort: true, sortDirection: DESCENDING } }; function applySortTo(field, filterSource) { logger.debug('sorting by field', field, 'current value of filterSource', filterSource); if (field === 'member') { filterSource.orderByField = 'memberId | memberIdToFullName : members : "" : true'; } else { filterSource.orderByField = field; } filterSource.reverseSort = !filterSource.reverseSort; filterSource.sortDirection = filterSource.reverseSort ? DESCENDING : ASCENDING; logger.debug('sorting by field', field, 'new value of filterSource', filterSource); } $scope.uploadSessionChanged = function () { notify.setBusy(); notify.hide(); refreshMemberUpdateAudit().then(notify.clearBusy); }; $scope.sortMembersUploadedBy = function (field) { applySortTo(field, $scope.filters.membersUploaded); }; $scope.sortMemberUpdateAuditBy = function (field) { applySortTo(field, $scope.filters.memberUpdateAudit); }; $scope.showMemberUpdateAuditColumn = function (field) { return s.startsWith($scope.filters.memberUpdateAudit.orderByField, field); }; $scope.showMembersUploadedColumn = function (field) { return $scope.filters.membersUploaded.orderByField === field; }; $scope.sortMembersBy = function (field) { applySortTo(field, $scope.filters.members); }; $scope.showMembersColumn = function (field) { return s.startsWith($scope.filters.members.orderByField, field); }; $scope.toGlyphicon = function (status) { if (status === 'created') return "glyphicon glyphicon-plus green-icon"; if (status === 'complete' || status === 'summary') return "glyphicon-ok green-icon"; if (status === 'success') return "glyphicon-ok-circle green-icon"; if (status === 'info') return "glyphicon-info-sign blue-icon"; if (status === 'updated') return "glyphicon glyphicon-pencil green-icon"; if (status === 'error') return "glyphicon-remove-circle red-icon"; if (status === 'skipped') return "glyphicon glyphicon-thumbs-up green-icon"; }; $scope.filters.members = { query: '', orderByField: 'firstName', reverseSort: false, sortDirection: ASCENDING, filterBy: [ { title: "Active Group Member", group: 'Group Settings', filter: function (member) { return member.groupMember; } }, { title: "All Members", filter: function () { return true; } }, { title: "Active Social Member", group: 'Group Settings', filter: MemberService.filterFor.SOCIAL_MEMBERS }, { title: "Membership Date Active/Not set", group: 'From Ramblers Supplied Datas', filter: function (member) { return !member.membershipExpiryDate || (member.membershipExpiryDate >= $scope.today); } }, { title: "Membership Date Expired", group: 'From Ramblers Supplied Data', filter: function (member) { return member.membershipExpiryDate < $scope.today; } }, { title: "Not received in last Ramblers Bulk Load", group: 'From Ramblers Supplied Data', filter: function (member) { return !member.receivedInLastBulkLoad; } }, { title: "Was received in last Ramblers Bulk Load", group: 'From Ramblers Supplied Data', filter: function (member) { return member.receivedInLastBulkLoad; } }, { title: "Password Expired", group: 'Other Settings', filter: function (member) { return member.expiredPassword; } }, { title: "Walk Admin", group: 'Administrators', filter: function (member) { return member.walkAdmin; } }, { title: "Walk Change Notifications", group: 'Administrators', filter: function (member) { return member.walkChangeNotifications; } }, { title: "Social Admin", group: 'Administrators', filter: function (member) { return member.socialAdmin; } }, { title: "Member Admin", group: 'Administrators', filter: function (member) { return member.memberAdmin; } }, { title: "Finance Admin", group: 'Administrators', filter: function (member) { return member.financeAdmin; } }, { title: "File Admin", group: 'Administrators', filter: function (member) { return member.fileAdmin; } }, { title: "Treasury Admin", group: 'Administrators', filter: function (member) { return member.treasuryAdmin; } }, { title: "Content Admin", group: 'Administrators', filter: function (member) { return member.contentAdmin; } }, { title: "Committee Member", group: 'Administrators', filter: function (member) { return member.committee; } }, { title: "Subscribed to the General emails list", group: 'Email Subscriptions', filter: MemberService.filterFor.GENERAL_MEMBERS_SUBSCRIBED }, { title: "Subscribed to the Walks email list", group: 'Email Subscriptions', filter: MemberService.filterFor.WALKS_MEMBERS_SUBSCRIBED }, { title: "Subscribed to the Social email list", group: 'Email Subscriptions', filter: MemberService.filterFor.SOCIAL_MEMBERS_SUBSCRIBED } ] }; $scope.filters.members.filterSelection = $scope.filters.members.filterBy[0].filter; $scope.memberAuditTabs = [ {title: "All Member Logins", active: true} ]; applyAllowEdits(); $scope.allowConfirmDelete = false; $scope.open = function ($event) { $event.preventDefault(); $event.stopPropagation(); $scope.opened = true; }; $scope.members = []; $scope.memberAudit = []; $scope.memberUpdateAudit = []; $scope.membersUploaded = []; $scope.resetAllBatchSubscriptions = function () { // careful with calling this - it resets all batch subscriptions to default values return EmailSubscriptionService.resetAllBatchSubscriptions($scope.members, false); }; function updateWalksList(members) { return EmailSubscriptionService.createBatchSubscriptionForList('walks', members); } function updateSocialEventsList(members) { return EmailSubscriptionService.createBatchSubscriptionForList('socialEvents', members); } function updateGeneralList(members) { return EmailSubscriptionService.createBatchSubscriptionForList('general', members); } function notifyUpdatesComplete(members) { notify.success({title: 'Mailchimp updates', message: 'Mailchimp lists were updated successfully'}); $scope.members = members; notify.clearBusy(); } $scope.deleteMemberAudit = function (filteredMemberAudit) { removeAllRecordsAndRefresh(filteredMemberAudit, refreshMemberAudit, 'member audit'); }; $scope.deleteMemberUpdateAudit = function (filteredMemberUpdateAudit) { removeAllRecordsAndRefresh(filteredMemberUpdateAudit, refreshMemberUpdateAudit, 'member update audit'); }; function removeAllRecordsAndRefresh(records, refreshFunction, type) { notify.success('Deleting ' + records.length + ' ' + type + ' record(s)'); var removePromises = []; angular.forEach(records, function (record) { removePromises.push(record.$remove()) }); $q.all(removePromises).then(function () { notify.success('Deleted ' + records.length + ' ' + type + ' record(s)'); refreshFunction.apply(); }); } $scope.$on('memberLoginComplete', function () { applyAllowEdits('memberLoginComplete'); refreshMembers(); refreshMemberAudit(); refreshMemberBulkLoadAudit() .then(refreshMemberUpdateAudit); }); $scope.$on('memberSaveComplete', function () { refreshMembers(); }); $scope.$on('memberLogoutComplete', function () { applyAllowEdits('memberLogoutComplete'); }); $scope.createMemberFromAudit = function (memberFromAudit) { var member = new MemberService(memberFromAudit); EmailSubscriptionService.defaultMailchimpSettings(member, true); member.groupMember = true; showMemberDialog(member, 'Add New'); notify.warning({ title: 'Recreating Member', message: "Note that clicking Save immediately on this member is likely to cause the same error to occur as was originally logged in the audit. Therefore make the necessary changes here to allow the member record to be saved successfully" }) }; $scope.addMember = function () { var member = new MemberService(); EmailSubscriptionService.defaultMailchimpSettings(member, true); member.groupMember = true; showMemberDialog(member, 'Add New'); }; $scope.viewMember = function (member) { showMemberDialog(member, 'View'); }; $scope.editMember = function (member) { showMemberDialog(member, 'Edit Existing'); }; $scope.deleteMemberDetails = function () { $scope.allowDelete = false; $scope.allowConfirmDelete = true; }; function unsubscribeWalksList() { return MailchimpListService.batchUnsubscribeMembers('walks', $scope.members, notify.success); } function unsubscribeSocialEventsList(members) { return MailchimpListService.batchUnsubscribeMembers('socialEvents', members, notify.success); } function unsubscribeGeneralList(members) { return MailchimpListService.batchUnsubscribeMembers('general', members, notify.success); } $scope.updateMailchimpLists = function () { $scope.display.saveInProgress = true; return $q.when(notify.success('Sending updates to Mailchimp lists', true)) .then(refreshMembers, notify.error, notify.success) .then(updateWalksList, notify.error, notify.success) .then(updateSocialEventsList, notify.error, notify.success) .then(updateGeneralList, notify.error, notify.success) .then(unsubscribeWalksList, notify.error, notify.success) .then(unsubscribeSocialEventsList, notify.error, notify.success) .then(unsubscribeGeneralList, notify.error, notify.success) .then(notifyUpdatesComplete, notify.error, notify.success) .then(resetSendFlags) .catch(mailchimpError); }; function mailchimpError(errorResponse) { resetSendFlags(); notify.error({ title: 'Mailchimp updates failed', message: (errorResponse.message || errorResponse) + (errorResponse.error ? ('. Error was: ' + ErrorMessageService.stringify(errorResponse.error)) : '') }); notify.clearBusy(); } $scope.confirmDeleteMemberDetails = function () { $scope.currentMember.$remove(hideMemberDialogAndRefreshMembers); }; $scope.cancelMemberDetails = function () { hideMemberDialogAndRefreshMembers(); }; $scope.profileSettingsConfirmedChecked = function () { ProfileConfirmationService.processMember($scope.currentMember); }; $scope.refreshMemberAudit = refreshMemberAudit; $scope.memberUrl = function () { return $scope.currentMember && $scope.currentMember.$id && (MONGOLAB_CONFIG.baseUrl + MONGOLAB_CONFIG.database + '/collections/members/' + $scope.currentMember.$id()); }; $scope.saveMemberDetails = function () { var member = DateUtils.convertDateFieldInObject($scope.currentMember, 'membershipExpiryDate'); $scope.display.saveInProgress = true; if (!member.userName) { member.userName = MemberNamingService.createUniqueUserName(member, $scope.members); logger.debug('creating username', member.userName); } if (!member.displayName) { member.displayName = MemberNamingService.createUniqueDisplayName(member, $scope.members); logger.debug('creating displayName', member.displayName); } function preProcessMemberBeforeSave() { DbUtils.removeEmptyFieldsIn(member); return EmailSubscriptionService.resetUpdateStatusForMember(member); } function removeEmptyFieldsIn(obj) { _.each(obj, function (value, field) { logger.debug('processing', typeof(field), 'field', field, 'value', value); if (_.contains([null, undefined, ""], value)) { logger.debug('removing non-populated', typeof(field), 'field', field); delete obj[field]; } }); } function saveAndHide() { return DbUtils.auditedSaveOrUpdate(member, hideMemberDialogAndRefreshMembers, notify.error) } $q.when(notify.success('Saving member', true)) .then(preProcessMemberBeforeSave, notify.error, notify.success) .then(saveAndHide, notify.error, notify.success) .then(resetSendFlags) .then(function () { return notify.success('Member saved successfully'); }) .catch(handleSaveError) }; $scope.copyDetailsToNewMember = function () { var copiedMember = new MemberService($scope.currentMember); delete copiedMember._id; EmailSubscriptionService.defaultMailchimpSettings(copiedMember, true); ProfileConfirmationService.unconfirmProfile(copiedMember); showMemberDialog(copiedMember, 'Copy Existing'); notify.success('Existing Member copied! Make changes here and save to create new member.') }; function applyAllowEdits() { $scope.allowEdits = LoggedInMemberService.allowMemberAdminEdits(); $scope.allowCopy = LoggedInMemberService.allowMemberAdminEdits(); return true; } function findLastLoginTimeForMember(member) { var memberAudit = _.chain($scope.memberAudit) .filter(function (memberAudit) { return memberAudit.userName === member.userName; }) .sortBy(function (memberAudit) { return memberAudit.lastLoggedIn; }) .last() .value(); return memberAudit === undefined ? undefined : memberAudit.loginTime; } $scope.bulkUploadRamblersDataStart = function () { $('#select-bulk-load-file').click(); }; $scope.resetSendFlagsAndNotifyError = function (error) { logger.error('resetSendFlagsAndNotifyError', error); resetSendFlags(); return notify.error(error); }; $scope.bulkUploadRamblersDataOpenFile = function (file) { if (file) { var fileUpload = file; $scope.display.saveInProgress = true; function bulkUploadRamblersResponse(memberBulkLoadServerResponse) { return MemberBulkUploadService.processMembershipRecords(file, memberBulkLoadServerResponse, $scope.members, notify) } function bulkUploadRamblersProgress(evt) { fileUpload.progress = parseInt(100.0 * evt.loaded / evt.total); logger.debug("bulkUploadRamblersProgress:progress event", evt); } $scope.uploadedFile = Upload.upload({ url: 'uploadRamblersData', method: 'POST', file: file }).then(bulkUploadRamblersResponse, $scope.resetSendFlagsAndNotifyError, bulkUploadRamblersProgress) .then(refreshMemberBulkLoadAudit) .then(refreshMemberUpdateAudit) .then(validateBulkUploadProcessingBeforeMailchimpUpdates) .catch($scope.resetSendFlagsAndNotifyError); } }; function showMemberDialog(member, memberEditMode) { logger.debug('showMemberDialog:', memberEditMode, member); $scope.alertTypeResetPassword = false; var existingRecordEditEnabled = $scope.allowEdits && s.startsWith(memberEditMode, 'Edit'); $scope.allowConfirmDelete = false; $scope.allowCopy = existingRecordEditEnabled; $scope.allowDelete = existingRecordEditEnabled; $scope.memberEditMode = memberEditMode; $scope.currentMember = member; $scope.currentMemberUpdateAudit = []; if ($scope.currentMember.$id()) { logger.debug('querying MemberUpdateAuditService for memberId', $scope.currentMember.$id()); MemberUpdateAuditService.query({memberId: $scope.currentMember.$id()}, {sort: {updateTime: -1}}) .then(function (data) { logger.debug('MemberUpdateAuditService:', data.length, 'events', data); $scope.currentMemberUpdateAudit = data; }); $scope.lastLoggedIn = findLastLoginTimeForMember(member); } else { logger.debug('new member with default values', $scope.currentMember); } $('#member-admin-dialog').modal(); } function hideMemberDialogAndRefreshMembers() { $q.when($('#member-admin-dialog').modal('hide')) .then(refreshMembers) .then(notify.clearBusy) .then(notify.hide) } function refreshMembers() { if (LoggedInMemberService.allowMemberAdminEdits()) { return MemberService.all() .then(function (refreshedMembers) { $scope.members = refreshedMembers; return $scope.members; }); } } function refreshMemberAudit() { if (LoggedInMemberService.allowMemberAdminEdits()) { MemberAuditService.all({limit: 100, sort: {loginTime: -1}}).then(function (memberAudit) { logger.debug('refreshed', memberAudit && memberAudit.length, 'member audit records'); $scope.memberAudit = memberAudit; }); } return true; } function refreshMemberBulkLoadAudit() { if (LoggedInMemberService.allowMemberAdminEdits()) { return MemberBulkLoadAuditService.all({limit: 100, sort: {createdDate: -1}}).then(function (uploadSessions) { logger.debug('refreshed', uploadSessions && uploadSessions.length, 'upload sessions'); $scope.uploadSessions = uploadSessions; $scope.filters.uploadSession.selected = _.first(uploadSessions); return $scope.filters.uploadSession.selected; }); } else { return true; } } function migrateAudits() { // temp - remove this! MemberUpdateAuditService.all({ limit: 10000, sort: {updateTime: -1} }).then(function (allMemberUpdateAudit) { logger.debug('temp queried all', allMemberUpdateAudit && allMemberUpdateAudit.length, 'member audit records'); var keys = []; var memberUpdateAuditServicePromises = []; var memberBulkLoadAuditServicePromises = []; var bulkAudits = _.chain(allMemberUpdateAudit) // .filter(function (audit) { // return !audit.uploadSessionId; // }) .map(function (audit) { var auditLog = { fileName: audit.fileName, createdDate: DateUtils.asValueNoTime(audit.updateTime), auditLog: [ { "status": "complete", "message": "Migrated audit log for upload of file " + audit.fileName } ] }; return auditLog; }) .uniq(JSON.stringify) .map(function (auditLog) { return new MemberBulkLoadAuditService(auditLog).$save() .then(function (auditResponse) { memberBulkLoadAuditServicePromises.push(auditResponse); logger.debug('saved bulk load session id', auditResponse.$id(), 'number', memberBulkLoadAuditServicePromises.length); return auditResponse; }); }) .value(); function saveAudit(audit) { memberUpdateAuditServicePromises.push(audit.$saveOrUpdate()); logger.debug('saved', audit.uploadSessionId, 'to audit number', memberUpdateAuditServicePromises.length); } $q.all(bulkAudits).then(function (savedBulkAuditRecords) { logger.debug('saved bulk load sessions', savedBulkAuditRecords); _.each(allMemberUpdateAudit, function (audit) { var parentBulkAudit = _.findWhere(savedBulkAuditRecords, { fileName: audit.fileName, createdDate: DateUtils.asValueNoTime(audit.updateTime) }); if (parentBulkAudit) { audit.uploadSessionId = parentBulkAudit.$id(); saveAudit(audit); } else { logger.error('no match for audit record', audit); } }); $q.all(memberUpdateAuditServicePromises).then(function (values) { logger.debug('saved', values.length, 'audit records'); }); }); }); } function refreshMemberUpdateAudit() { if (LoggedInMemberService.allowMemberAdminEdits()) { // migrateAudits(); if ($scope.filters.uploadSession.selected && $scope.filters.uploadSession.selected.$id) { var uploadSessionId = $scope.filters.uploadSession.selected.$id(); var query = {uploadSessionId: uploadSessionId}; if ($scope.filters.memberUpdateAudit.query.status) { angular.extend(query, {memberAction: $scope.filters.memberUpdateAudit.query.status}) } logger.debug('querying member audit records with', query); return MemberUpdateAuditService.query(query, {sort: {updateTime: -1}}).then(function (memberUpdateAudit) { $scope.memberUpdateAudit = memberUpdateAudit; logger.debug('refreshed', memberUpdateAudit && memberUpdateAudit.length, 'member audit records'); return $scope.memberUpdateAudit; }); } else { $scope.memberUpdateAudit = []; logger.debug('no member audit records'); return $q.when($scope.memberUpdateAudit); } } } function auditSummary() { return _.groupBy($scope.memberUpdateAudit, function (auditItem) { return auditItem.memberAction || 'unknown'; }); } function auditSummaryFormatted(auditSummary) { var total = _.reduce(auditSummary, function (memo, value) { return memo + value.length; }, 0); var summary = _.map(auditSummary, function (items, key) { return items.length + ':' + key; }).join(', '); return total + " Member audits " + (total ? '(' + summary + ')' : ''); } $scope.memberUpdateAuditSummary = function () { return auditSummaryFormatted(auditSummary()); }; function validateBulkUploadProcessingBeforeMailchimpUpdates() { logger.debug('validateBulkUploadProcessing:$scope.filters.uploadSession', $scope.filters.uploadSession); if ($scope.filters.uploadSession.selected.error) { notify.error({title: 'Bulk upload failed', message: $scope.filters.uploadSession.selected.error}); } else { var summary = auditSummary(); var summaryFormatted = auditSummaryFormatted(summary); logger.debug('summary', summary, 'summaryFormatted', summaryFormatted); if (summary.error) { notify.error({ title: "Bulk upload was not successful", message: "One or more errors occurred - " + summaryFormatted }); return false; } else return $scope.updateMailchimpLists(); } } }] ) ; /* concatenated from client/src/app/js/memberAdminSendEmailsController.js */ angular.module('ekwgApp') .controller('MemberAdminSendEmailsController', ["$log", "$q", "$scope", "$filter", "DateUtils", "DbUtils", "LoggedInMemberService", "ErrorMessageService", "EmailSubscriptionService", "MailchimpSegmentService", "MailchimpCampaignService", "MailchimpConfig", "Notifier", "members", "close", function ($log, $q, $scope, $filter, DateUtils, DbUtils, LoggedInMemberService, ErrorMessageService, EmailSubscriptionService, MailchimpSegmentService, MailchimpCampaignService, MailchimpConfig, Notifier, members, close) { var logger = $log.getInstance('MemberAdminSendEmailsController'); $log.logLevels['MemberAdminSendEmailsController'] = $log.LEVEL.OFF; var notify = Notifier($scope); notify.setBusy(); var CAMPAIGN_TYPE_WELCOME = "welcome"; var CAMPAIGN_TYPE_PASSWORD_RESET = "passwordReset"; var CAMPAIGN_TYPE_EXPIRED_MEMBERS_WARNING = "expiredMembersWarning"; var CAMPAIGN_TYPE_EXPIRED_MEMBERS = "expiredMembers"; $scope.today = DateUtils.momentNowNoTime().valueOf(); $scope.members = members; $scope.memberFilterDateCalendar = { open: function ($event) { $event.preventDefault(); $event.stopPropagation(); $scope.memberFilterDateCalendar.opened = true; } }; $scope.showHelp = function (show) { $scope.display.showHelp = show; }; $scope.cancel = function () { close(); }; $scope.display = { showHelp: false, selectableMembers: [], emailMembers: [], saveInProgress: false, monthsInPast: 1, memberFilterDate: undefined, emailType: {name: "(loading)"}, passwordResetCaption: function () { return 'About to send a ' + $scope.display.emailType.name + ' to ' + $scope.display.emailMembers.length + ' member' + ($scope.display.emailMembers.length === 1 ? '' : 's'); }, expiryEmailsSelected: function () { var returnValue = $scope.display.emailType.type === CAMPAIGN_TYPE_EXPIRED_MEMBERS_WARNING || $scope.display.emailType.type === CAMPAIGN_TYPE_EXPIRED_MEMBERS; logger.debug('expiryEmailsSelected -> ', returnValue); return returnValue; }, recentMemberEmailsSelected: function () { return $scope.display.emailType.type === CAMPAIGN_TYPE_WELCOME || $scope.display.emailType.type === CAMPAIGN_TYPE_PASSWORD_RESET; } }; $scope.populateSelectableMembers = function () { $scope.display.selectableMembers = _.chain($scope.members) .filter(function (member) { return EmailSubscriptionService.includeMemberInEmailList('general', member); }) .map(extendWithInformation) .value(); logger.debug('populateSelectableMembers:found', $scope.display.selectableMembers.length, 'members'); }; $scope.populateSelectableMembers(); $scope.calculateMemberFilterDate = function () { $scope.display.memberFilterDate = DateUtils.momentNowNoTime().subtract($scope.display && $scope.display.emailType.monthsInPast, 'months').valueOf(); }; $scope.clearDisplayEmailMembers = function () { $scope.display.emailMembers = []; notify.warning({ title: 'Member selection', message: 'current member selection was cleared' }); }; function extendWithInformation(member) { return $scope.display.expiryEmailsSelected() ? extendWithExpiryInformation(member) : extendWithCreatedInformation(member); } function extendWithExpiryInformation(member) { var expiredActive = member.membershipExpiryDate < $scope.today ? 'expired' : 'active'; var memberGrouping = member.receivedInLastBulkLoad ? expiredActive : 'missing from last bulk load'; var datePrefix = memberGrouping === 'expired' ? ': ' : ', ' + (member.membershipExpiryDate < $scope.today ? 'expired' : 'expiry') + ': '; var text = $filter('fullNameWithAlias')(member) + ' (' + memberGrouping + datePrefix + (DateUtils.displayDate(member.membershipExpiryDate) || 'not known') + ')'; return angular.extend({}, member, {id: member.$id(), text: text, memberGrouping: memberGrouping}); } function extendWithCreatedInformation(member) { var memberGrouping = member.membershipExpiryDate < $scope.today ? 'expired' : 'active'; var text = $filter('fullNameWithAlias')(member) + ' (created ' + (DateUtils.displayDate(member.createdDate) || 'not known') + ')'; return angular.extend({}, member, {id: member.$id(), text: text, memberGrouping: memberGrouping}); } $scope.memberGrouping = function (member) { return member.memberGrouping; }; function populateMembersBasedOnFilter(filter) { logger.debug('populateExpiredMembers: display.emailType ->', $scope.display.emailType); notify.setBusy(); notify.warning({ title: 'Automatically adding expired members', message: ' - please wait for list to be populated' }); $scope.display.memberFilterDate = DateUtils.convertDateField($scope.display.memberFilterDate); $scope.display.emailMembers = _($scope.display.selectableMembers) .filter(filter); notify.warning({ title: 'Members added to email selection', message: 'automatically added ' + $scope.display.emailMembers.length + ' members' }); notify.clearBusy(); } $scope.populateMembers = function (recalcMemberFilterDate) { logger.debug('$scope.display.memberSelection', $scope.display.emailType.memberSelection); this.populateSelectableMembers(); switch ($scope.display.emailType.memberSelection) { case 'recently-added': $scope.populateRecentlyAddedMembers(recalcMemberFilterDate); break; case 'expired-members': $scope.populateExpiredMembers(recalcMemberFilterDate); break } }; $scope.populateRecentlyAddedMembers = function (recalcMemberFilterDate) { if (recalcMemberFilterDate) { $scope.calculateMemberFilterDate(); } populateMembersBasedOnFilter(function (member) { return member.groupMember && (member.createdDate >= $scope.display.memberFilterDate); }); }; $scope.populateExpiredMembers = function (recalcMemberFilterDate) { if (recalcMemberFilterDate) { $scope.calculateMemberFilterDate(); } populateMembersBasedOnFilter(function (member) { return member.groupMember && member.membershipExpiryDate && (member.membershipExpiryDate < $scope.display.memberFilterDate); }); }; $scope.populateMembersMissingFromBulkLoad = function (recalcMemberFilterDate) { if (recalcMemberFilterDate) { $scope.calculateMemberFilterDate(); } populateMembersBasedOnFilter(function (member) { return member.groupMember && member.membershipExpiryDate && !member.receivedInLastBulkLoad; }) }; function displayEmailMembersToMembers() { return _.chain($scope.display.emailMembers) .map(function (memberId) { return _.find($scope.members, function (member) { return member.$id() === memberId.id; }) }) .filter(function (member) { return member && member.email; }).value(); } function addPasswordResetIdToMembers() { var saveMemberPromises = []; _.map(displayEmailMembersToMembers(), function (member) { LoggedInMemberService.setPasswordResetId(member); EmailSubscriptionService.resetUpdateStatusForMember(member); saveMemberPromises.push(DbUtils.auditedSaveOrUpdate(member)) }); return $q.all(saveMemberPromises).then(function () { return notify.success('Password reset prepared for ' + saveMemberPromises.length + ' member(s)'); }); } function includeInNextMailchimpListUpdate() { var saveMemberPromises = []; _.map(displayEmailMembersToMembers(), function (member) { EmailSubscriptionService.resetUpdateStatusForMember(member); saveMemberPromises.push(DbUtils.auditedSaveOrUpdate(member)) }); return $q.all(saveMemberPromises).then(function () { return notify.success('Member expiration prepared for ' + saveMemberPromises.length + ' member(s)'); }); } function noAction() { } function removeExpiredMembersFromGroup() { logger.debug('removing ', $scope.display.emailMembers.length, 'members from group'); var saveMemberPromises = []; _($scope.display.emailMembers) .map(function (memberId) { return _.find($scope.members, function (member) { return member.$id() === memberId.id; }) }).map(function (member) { member.groupMember = false; EmailSubscriptionService.resetUpdateStatusForMember(member); saveMemberPromises.push(DbUtils.auditedSaveOrUpdate(member)) }); return $q.all(saveMemberPromises) .then(function () { return notify.success('EKWG group membership removed for ' + saveMemberPromises.length + ' member(s)'); }) } $scope.cancelSendEmails = function () { $scope.cancel(); }; $scope.sendEmailsDisabled = function () { return $scope.display.emailMembers.length === 0 }; $scope.sendEmails = function () { $scope.alertTypeResetPassword = true; $scope.display.saveInProgress = true; $scope.display.duplicate = false; $q.when(notify.success('Preparing to email ' + $scope.display.emailMembers.length + ' member' + ($scope.display.emailMembers.length === 1 ? '' : 's'), true)) .then($scope.display.emailType.preSend) .then(updateGeneralList) .then(createOrSaveMailchimpSegment) .then(saveSegmentDataToMailchimpConfig) .then(sendEmailCampaign) .then($scope.display.emailType.postSend) .then(notify.clearBusy) .then($scope.cancel) .then(resetSendFlags) .catch(handleSendError); }; function resetSendFlags() { logger.debug('resetSendFlags'); $scope.display.saveInProgress = false; } function updateGeneralList() { return EmailSubscriptionService.createBatchSubscriptionForList('general', $scope.members).then(function (updatedMembers) { $scope.members = updatedMembers; }); } function createOrSaveMailchimpSegment() { return MailchimpSegmentService.saveSegment('general', {segmentId: $scope.display.emailType.segmentId}, $scope.display.emailMembers, $scope.display.emailType.name, $scope.members); } function saveSegmentDataToMailchimpConfig(segmentResponse) { logger.debug('saveSegmentDataToMailchimpConfig:segmentResponse', segmentResponse); return MailchimpConfig.getConfig() .then(function (config) { config.mailchimp.segments.general[$scope.display.emailType.type + 'SegmentId'] = segmentResponse.segment.id; return MailchimpConfig.saveConfig(config) .then(function () { logger.debug('saveSegmentDataToMailchimpConfig:returning segment id', segmentResponse.segment.id); return segmentResponse.segment.id; }); }); } function sendEmailCampaign(segmentId) { var members = $scope.display.emailMembers.length + ' member(s)'; notify.success('Sending ' + $scope.display.emailType.name + ' email to ' + members); logger.debug('about to sendEmailCampaign:', $scope.display.emailType.type, 'campaign Id', $scope.display.emailType.campaignId, 'segmentId', segmentId, 'campaignName', $scope.display.emailType.name); return MailchimpCampaignService.replicateAndSendWithOptions({ campaignId: $scope.display.emailType.campaignId, campaignName: $scope.display.emailType.name, segmentId: segmentId }).then(function () { notify.success('Sending of ' + $scope.display.emailType.name + ' to ' + members + ' was successful'); }); } $scope.emailMemberList = function () { return _($scope.display.emailMembers) .sortBy(function (emailMember) { return emailMember.text; }).map(function (emailMember) { return emailMember.text; }).join(', '); }; function handleSendError(errorResponse) { $scope.display.saveInProgress = false; notify.error({ title: 'Your notification could not be sent', message: (errorResponse.message || errorResponse) + (errorResponse.error ? ('. Error was: ' + ErrorMessageService.stringify(errorResponse.error)) : '') }); notify.clearBusy(); } MailchimpConfig.getConfig() .then(function (config) { $scope.display.emailTypes = [ { preSend: addPasswordResetIdToMembers, type: CAMPAIGN_TYPE_WELCOME, name: config.mailchimp.campaigns.welcome.name, monthsInPast: config.mailchimp.campaigns.welcome.monthsInPast, campaignId: config.mailchimp.campaigns.welcome.campaignId, segmentId: config.mailchimp.segments.general.welcomeSegmentId, memberSelection: 'recently-added', postSend: noAction, dateTooltip: "All members created in the last " + config.mailchimp.campaigns.welcome.monthsInPast + " month are displayed as a default, as these are most likely to need a welcome email sent" }, { preSend: addPasswordResetIdToMembers, type: CAMPAIGN_TYPE_PASSWORD_RESET, name: config.mailchimp.campaigns.passwordReset.name, monthsInPast: config.mailchimp.campaigns.passwordReset.monthsInPast, campaignId: config.mailchimp.campaigns.passwordReset.campaignId, segmentId: config.mailchimp.segments.general.passwordResetSegmentId, memberSelection: 'recently-added', postSend: noAction, dateTooltip: "All members created in the last " + config.mailchimp.campaigns.passwordReset.monthsInPast + " month are displayed as a default" }, { preSend: includeInNextMailchimpListUpdate, type: CAMPAIGN_TYPE_EXPIRED_MEMBERS_WARNING, name: config.mailchimp.campaigns.expiredMembersWarning.name, monthsInPast: config.mailchimp.campaigns.expiredMembersWarning.monthsInPast, campaignId: config.mailchimp.campaigns.expiredMembersWarning.campaignId, segmentId: config.mailchimp.segments.general.expiredMembersWarningSegmentId, memberSelection: 'expired-members', postSend: noAction, dateTooltip: "Using the expiry date field, you can choose which members will automatically be included. " + "A date " + config.mailchimp.campaigns.expiredMembersWarning.monthsInPast + " months in the past has been pre-selected, to avoid including members whose membership renewal is still progress" }, { preSend: includeInNextMailchimpListUpdate, type: CAMPAIGN_TYPE_EXPIRED_MEMBERS, name: config.mailchimp.campaigns.expiredMembers.name, monthsInPast: config.mailchimp.campaigns.expiredMembers.monthsInPast, campaignId: config.mailchimp.campaigns.expiredMembers.campaignId, segmentId: config.mailchimp.segments.general.expiredMembersSegmentId, memberSelection: 'expired-members', postSend: removeExpiredMembersFromGroup, dateTooltip: "Using the expiry date field, you can choose which members will automatically be included. " + "A date 3 months in the past has been pre-selected, to avoid including members whose membership renewal is still progress" } ]; $scope.display.emailType = $scope.display.emailTypes[0]; $scope.populateMembers(true); }); }] ); /* concatenated from client/src/app/js/memberResources.js */ angular.module('ekwgApp') .factory('MemberResourcesService', ["$mongolabResourceHttp", function ($mongolabResourceHttp) { return $mongolabResourceHttp('memberResources'); }]) .factory('MemberResourcesReferenceData', ["$log", "URLService", "ContentMetaDataService", "FileUtils", "LoggedInMemberService", "SiteEditService", function ($log, URLService, ContentMetaDataService, FileUtils, LoggedInMemberService, SiteEditService) { var logger = $log.getInstance('MemberResourcesReferenceData'); $log.logLevels['MemberResourcesReferenceData'] = $log.LEVEL.OFF; const subjects = [ { id: "newsletter", description: "Newsletter" }, { id: "siteReleaseNote", description: "Site Release Note" }, { id: "walkPlanning", description: "Walking Planning Advice" } ]; const resourceTypes = [ { id: "email", description: "Email", action: "View email", icon: function () { return "assets/images/local/mailchimp.ico" }, resourceUrl: function (memberResource) { var data = _.property(['data', 'campaign', 'archive_url_long'])(memberResource); logger.debug('email:resourceUrl for', memberResource, data); return data; } }, { id: "file", description: "File", action: "Download", icon: function (memberResource) { return FileUtils.icon(memberResource, 'data') }, resourceUrl: function (memberResource) { var data = memberResource && memberResource.data.fileNameData ? URLService.baseUrl() + ContentMetaDataService.baseUrl("memberResources") + "/" + memberResource.data.fileNameData.awsFileName : ""; logger.debug('file:resourceUrl for', memberResource, data); return data; } }, { id: "url", action: "View page", description: "External Link", icon: function () { return "assets/images/ramblers/favicon.ico" }, resourceUrl: function () { return "TBA"; } } ]; const accessLevels = [ { id: "hidden", description: "Hidden", filter: function () { return SiteEditService.active() || false; } }, { id: "committee", description: "Committee", filter: function () { return SiteEditService.active() || LoggedInMemberService.allowCommittee(); } }, { id: "loggedInMember", description: "Logged-in member", filter: function () { return SiteEditService.active() || LoggedInMemberService.memberLoggedIn(); } }, { id: "public", description: "Public", filter: function () { return true; } }]; function resourceTypeFor(resourceType) { var type = _.find(resourceTypes, function (type) { return type.id === resourceType; }); logger.debug('resourceType for', type, type); return type; } function accessLevelFor(accessLevel) { var level = _.find(accessLevels, function (level) { return level.id === accessLevel; }); logger.debug('accessLevel for', accessLevel, level); return level; } return { subjects: subjects, resourceTypes: resourceTypes, accessLevels: accessLevels, resourceTypeFor: resourceTypeFor, accessLevelFor: accessLevelFor }; }]); /* concatenated from client/src/app/js/memberServices.js */ angular.module('ekwgApp') .factory('MemberUpdateAuditService', ["$mongolabResourceHttp", function ($mongolabResourceHttp) { return $mongolabResourceHttp('memberUpdateAudit'); }]) .factory('MemberBulkLoadAuditService', ["$mongolabResourceHttp", function ($mongolabResourceHttp) { return $mongolabResourceHttp('memberBulkLoadAudit'); }]) .factory('MemberAuditService', ["$mongolabResourceHttp", function ($mongolabResourceHttp) { return $mongolabResourceHttp('memberAudit'); }]) .factory('ExpenseClaimsService', ["$mongolabResourceHttp", function ($mongolabResourceHttp) { return $mongolabResourceHttp('expenseClaims'); }]) .factory('MemberNamingService', ["$log", "StringUtils", function ($log, StringUtils) { var logger = $log.getInstance('MemberNamingService'); $log.logLevels['MemberNamingService'] = $log.LEVEL.OFF; var createUserName = function (member) { return StringUtils.replaceAll(' ', '', (member.firstName + '.' + member.lastName).toLowerCase()); }; function createDisplayName(member) { return member.firstName.trim() + ' ' + member.lastName.trim().substring(0, 1).toUpperCase(); } function createUniqueUserName(member, members) { return createUniqueValueFrom(createUserName, 'userName', member, members) } function createUniqueDisplayName(member, members) { return createUniqueValueFrom(createDisplayName, 'displayName', member, members) } function createUniqueValueFrom(nameFunction, field, member, members) { var attempts = 0; var suffix = ""; while (true) { var createdName = nameFunction(member) + suffix; if (!memberFieldExists(field, createdName, members)) { return createdName } else { attempts++; suffix = attempts; } } } function memberFieldExists(field, value, members) { var member = _(members).find(function (member) { return member[field] === value; }); var returnValue = member && member[field]; logger.debug('field', field, 'matching', value, member, '->', returnValue); return returnValue; } return { createDisplayName: createDisplayName, createUserName: createUserName, createUniqueUserName: createUniqueUserName, createUniqueDisplayName: createUniqueDisplayName }; }]) .factory('MemberService', ["$mongolabResourceHttp", "$log", function ($mongolabResourceHttp, $log) { var logger = $log.getInstance('MemberService'); var noLogger = $log.getInstance('MemberServiceMuted'); $log.logLevels['MemberServiceMuted'] = $log.LEVEL.OFF; $log.logLevels['MemberService'] = $log.LEVEL.OFF; var memberService = $mongolabResourceHttp('members'); memberService.filterFor = { SOCIAL_MEMBERS_SUBSCRIBED: function (member) { return member.groupMember && member.socialMember && member.mailchimpLists.socialEvents.subscribed }, WALKS_MEMBERS_SUBSCRIBED: function (member) { return member.groupMember && member.mailchimpLists.walks.subscribed }, GENERAL_MEMBERS_SUBSCRIBED: function (member) { return member.groupMember && member.mailchimpLists.general.subscribed }, GROUP_MEMBERS: function (member) { return member.groupMember; }, COMMITTEE_MEMBERS: function (member) { return member.groupMember && member.committee; }, SOCIAL_MEMBERS: function (member) { return member.groupMember && member.socialMember; }, }; memberService.allLimitedFields = function allLimitedFields(filterFunction) { return memberService.all({ fields: { mailchimpLists: 1, groupMember: 1, socialMember: 1, financeAdmin: 1, treasuryAdmin: 1, fileAdmin: 1, committee: 1, walkChangeNotifications: 1, email: 1, displayName: 1, contactId: 1, mobileNumber: 1, $id: 1, firstName: 1, lastName: 1, nameAlias: 1 } }).then(function (members) { return _.chain(members) .filter(filterFunction) .sortBy(function (member) { return member.firstName + member.lastName; }).value(); }); }; memberService.toMember = function (memberIdOrObject, members) { var memberId = (_.has(memberIdOrObject, 'id') ? memberIdOrObject.id : memberIdOrObject); noLogger.info('toMember:memberIdOrObject', memberIdOrObject, '->', memberId); var member = _.find(members, function (member) { return member.$id() === memberId; }); noLogger.info('toMember:', memberIdOrObject, '->', member); return member; }; memberService.allMemberMembersWithPrivilege = function (privilege, members) { var filteredMembers = _.filter(members, function (member) { return member.groupMember && member[privilege]; }); logger.debug('allMemberMembersWithPrivilege:privilege', privilege, 'filtered from', members.length, '->', filteredMembers.length, 'members ->', filteredMembers); return filteredMembers; }; memberService.allMemberIdsWithPrivilege = function (privilege, members) { return memberService.allMemberMembersWithPrivilege(privilege, members).map(extractMemberId); function extractMemberId(member) { return member.$id() } }; return memberService; }]); /* concatenated from client/src/app/js/notificationUrl.js */ angular.module("ekwgApp") .component("notificationUrl", { templateUrl: "partials/components/notification-url.html", controller: ["$log", "URLService", "FileUtils", function ($log, URLService, FileUtils) { var ctrl = this; var logger = $log.getInstance("NotificationUrlController"); $log.logLevels['NotificationUrlController'] = $log.LEVEL.OFF; ctrl.anchor_href = function () { return URLService.notificationHref(ctrl); }; ctrl.anchor_target = function () { return "_blank"; }; ctrl.anchor_text = function () { var text = (!ctrl.text && ctrl.name) ? FileUtils.basename(ctrl.name) : ctrl.text || ctrl.anchor_href(); logger.debug("text", text); return text; }; }], bindings: { name: "@", text: "@", type: "@", id: "@", area: "@" } }); /* concatenated from client/src/app/js/notifier.js */ angular.module('ekwgApp') .factory('Notifier', ["$log", "ErrorMessageService", function ($log, ErrorMessageService) { var ALERT_ERROR = {class: 'alert-danger', icon: 'glyphicon-exclamation-sign', failure: true}; var ALERT_WARNING = {class: 'alert-warning', icon: 'glyphicon-info-sign'}; var ALERT_INFO = {class: 'alert-success', icon: 'glyphicon-info-sign'}; var ALERT_SUCCESS = {class: 'alert-success', icon: 'glyphicon-ok'}; var logger = $log.getInstance('Notifier'); $log.logLevels['Notifier'] = $log.LEVEL.OFF; return function (scope) { scope.alertClass = ALERT_SUCCESS.class; scope.alert = ALERT_SUCCESS; scope.alertMessages = []; scope.alertHeading = []; scope.ready = false; function setReady() { clearBusy(); return scope.ready = true; } function clearBusy() { logger.debug('clearing busy'); return scope.busy = false; } function setBusy() { logger.debug('setting busy'); return scope.busy = true; } function showContactUs(state) { logger.debug('setting showContactUs', state); return scope.showContactUs = state; } function notifyAlertMessage(alertType, message, append, busy) { var messageText = message && ErrorMessageService.stringify(_.has(message, 'message') ? message.message : message); if (busy) setBusy(); if (!append || alertType === ALERT_ERROR) scope.alertMessages = []; if (messageText) scope.alertMessages.push(messageText); scope.alertTitle = message && _.has(message, 'title') ? message.title : undefined; scope.alert = alertType; scope.alertClass = alertType.class; scope.showAlert = scope.alertMessages.length > 0; scope.alertMessage = scope.alertMessages.join(', '); if (alertType === ALERT_ERROR && !_.has(message, 'continue')) { logger.error('notifyAlertMessage:', 'class =', alertType, 'messageText =', messageText, 'append =', append); clearBusy(); throw message; } else { return logger.debug('notifyAlertMessage:', 'class =', alertType, 'messageText =', messageText, 'append =', append, 'showAlert =', scope.showAlert); } } function progress(message, busy) { return notifyAlertMessage(ALERT_INFO, message, false, busy) } function hide() { notifyAlertMessage(ALERT_SUCCESS); return clearBusy(); } function success(message, busy) { return notifyAlertMessage(ALERT_SUCCESS, message, false, busy) } function successWithAppend(message, busy) { return notifyAlertMessage(ALERT_SUCCESS, message, true, busy) } function error(message, append, busy) { return notifyAlertMessage(ALERT_ERROR, message, append, busy) } function warning(message, append, busy) { return notifyAlertMessage(ALERT_WARNING, message, append, busy) } return { success: success, successWithAppend: successWithAppend, progress: progress, progressWithAppend: successWithAppend, error: error, warning: warning, showContactUs: showContactUs, setBusy: setBusy, clearBusy: clearBusy, setReady: setReady, hide: hide } } }]); /* concatenated from client/src/app/js/profile.js */ angular.module('ekwgApp') .factory('ProfileConfirmationService', ["$filter", "LoggedInMemberService", "DateUtils", function ($filter, LoggedInMemberService, DateUtils) { var confirmProfile = function (member) { if (member) { member.profileSettingsConfirmed = true; member.profileSettingsConfirmedAt = DateUtils.nowAsValue(); member.profileSettingsConfirmedBy = $filter('fullNameWithAlias')(LoggedInMemberService.loggedInMember()); } }; var unconfirmProfile = function (member) { if (member) { delete member.profileSettingsConfirmed; delete member.profileSettingsConfirmedAt; delete member.profileSettingsConfirmedBy; } }; var processMember = function (member) { if (member) { if (member.profileSettingsConfirmed) { confirmProfile(member) } else { unconfirmProfile(member) } } }; return { confirmProfile: confirmProfile, unconfirmProfile: unconfirmProfile, processMember: processMember }; }]) .controller('ProfileController', ["$q", "$rootScope", "$routeParams", "$scope", "LoggedInMemberService", "MemberService", "URLService", "ProfileConfirmationService", "EmailSubscriptionService", "CommitteeReferenceData", function ($q, $rootScope, $routeParams, $scope, LoggedInMemberService, MemberService, URLService, ProfileConfirmationService, EmailSubscriptionService, CommitteeReferenceData) { $scope.showArea = function (area) { URLService.navigateTo('admin', area) }; $scope.contactUs = { ready: function () { return CommitteeReferenceData.ready; } }; function isArea(area) { return (area === $routeParams.area); } var LOGIN_DETAILS = 'login details'; var PERSONAL_DETAILS = 'personal details'; var CONTACT_PREFERENCES = 'contact preferences'; var ALERT_CLASS_DANGER = 'alert-danger'; var ALERT_CLASS_SUCCESS = 'alert-success'; $scope.currentMember = {}; $scope.enteredMemberCredentials = {}; $scope.alertClass = ALERT_CLASS_SUCCESS; $scope.alertType = LOGIN_DETAILS; $scope.alertMessages = []; $scope.personalDetailsOpen = isArea('personal-details'); $scope.loginDetailsOpen = isArea('login-details'); $scope.contactPreferencesOpen = isArea('contact-preferences'); $scope.showAlertPersonalDetails = false; $scope.showAlertLoginDetails = false; $scope.showAlertContactPreferences = false; applyAllowEdits('controller init'); refreshMember(); $scope.$on('memberLoginComplete', function () { $scope.alertMessages = []; refreshMember(); applyAllowEdits('memberLoginComplete'); }); $scope.$on('memberLogoutComplete', function () { $scope.alertMessages = []; applyAllowEdits('memberLogoutComplete'); }); $scope.undoChanges = function () { refreshMember(); }; function saveOrUpdateSuccessful() { $scope.enteredMemberCredentials.newPassword = null; $scope.enteredMemberCredentials.newPasswordConfirm = null; $scope.alertMessages.push('Your ' + $scope.alertType + ' were saved successfully and will be effective on your next login.'); showAlert(ALERT_CLASS_SUCCESS, $scope.alertType); } function saveOrUpdateUnsuccessful(message) { var messageDefaulted = message || 'Please try again later.'; $scope.alertMessages.push('Changes to your ' + $scope.alertType + ' could not be saved. ' + messageDefaulted); showAlert(ALERT_CLASS_DANGER, $scope.alertType); } $scope.saveLoginDetails = function () { $scope.alertMessages = []; validateUserNameExistence(); }; $scope.$on('userNameExistenceCheckComplete', function () { validatePassword(); validateUserName(); if ($scope.alertMessages.length === 0) { saveMemberDetails(LOGIN_DETAILS) } else { showAlert(ALERT_CLASS_DANGER, LOGIN_DETAILS); } }); $scope.savePersonalDetails = function () { $scope.alertMessages = []; saveMemberDetails(PERSONAL_DETAILS); }; $scope.saveContactPreferences = function () { $scope.alertMessages = []; ProfileConfirmationService.confirmProfile($scope.currentMember); saveMemberDetails(CONTACT_PREFERENCES); }; $scope.loggedIn = function () { return LoggedInMemberService.memberLoggedIn(); }; function validatePassword() { if ($scope.enteredMemberCredentials.newPassword || $scope.enteredMemberCredentials.newPasswordConfirm) { // console.log('validating password change old=', $scope.enteredMemberCredentials.newPassword, 'new=', $scope.enteredMemberCredentials.newPasswordConfirm); if ($scope.currentMember.password === $scope.enteredMemberCredentials.newPassword) { $scope.alertMessages.push('The new password was the same as the old one.'); } else if ($scope.enteredMemberCredentials.newPassword !== $scope.enteredMemberCredentials.newPasswordConfirm) { $scope.alertMessages.push('The new password was not confirmed correctly.'); } else if ($scope.enteredMemberCredentials.newPassword.length < 6) { $scope.alertMessages.push('The new password needs to be at least 6 characters long.'); } else { $scope.currentMember.password = $scope.enteredMemberCredentials.newPassword; // console.log('validating password change - successful'); } } } function validateUserName() { if ($scope.enteredMemberCredentials.userName !== $scope.currentMember.userName) { $scope.enteredMemberCredentials.userName = $scope.enteredMemberCredentials.userName.trim(); if ($scope.enteredMemberCredentials.userName.length === 0) { $scope.alertMessages.push('The new user name cannot be blank.'); } else { $scope.currentMember.userName = $scope.enteredMemberCredentials.userName; } } } function undoChangesTo(alertType) { refreshMember(); $scope.alertMessages = ['Changes to your ' + alertType + ' were reverted.']; showAlert(ALERT_CLASS_SUCCESS, alertType); } $scope.undoLoginDetails = function () { undoChangesTo(LOGIN_DETAILS); }; $scope.undoPersonalDetails = function () { undoChangesTo(PERSONAL_DETAILS); }; $scope.undoContactPreferences = function () { undoChangesTo(CONTACT_PREFERENCES); }; function saveMemberDetails(alertType) { $scope.alertType = alertType; EmailSubscriptionService.resetUpdateStatusForMember($scope.currentMember); LoggedInMemberService.saveMember($scope.currentMember, saveOrUpdateSuccessful, saveOrUpdateUnsuccessful); } function showAlert(alertClass, alertType) { if ($scope.alertMessages.length > 0) { $scope.alertClass = alertClass; $scope.alertMessage = $scope.alertMessages.join(', '); $scope.showAlertLoginDetails = alertType === LOGIN_DETAILS; $scope.showAlertPersonalDetails = alertType === PERSONAL_DETAILS; $scope.showAlertContactPreferences = alertType === CONTACT_PREFERENCES; } else { $scope.showAlertLoginDetails = false; $scope.showAlertPersonalDetails = false; $scope.showAlertContactPreferences = false; } } function applyAllowEdits(event) { $scope.allowEdits = LoggedInMemberService.memberLoggedIn(); $scope.isAdmin = LoggedInMemberService.allowMemberAdminEdits(); } function refreshMember() { if (LoggedInMemberService.memberLoggedIn()) { LoggedInMemberService.getMemberForUserName(LoggedInMemberService.loggedInMember().userName) .then(function (member) { if (!_.isEmpty(member)) { $scope.currentMember = member; $scope.enteredMemberCredentials = {userName: $scope.currentMember.userName}; } else { $scope.alertMessages.push('Could not refresh member'); showAlert(ALERT_CLASS_DANGER, LOGIN_DETAILS); } }, function (response) { $scope.alertMessages.push('Unexpected error occurred: ' + response); showAlert(ALERT_CLASS_DANGER, LOGIN_DETAILS); }) } } function validateUserNameExistence() { if ($scope.enteredMemberCredentials.userName !== $scope.currentMember.userName) { LoggedInMemberService.getMemberForUserName($scope.enteredMemberCredentials.userName) .then(function (member) { if (!_.isEmpty(member)) { $scope.alertMessages.push('The user name ' + $scope.enteredMemberCredentials.userName + ' is already used by another member. Please choose another.'); $scope.enteredMemberCredentials.userName = $scope.currentMember.userName; } $rootScope.$broadcast('userNameExistenceCheckComplete'); }, function (response) { $scope.alertMessages.push('Unexpected error occurred: ' + response); showAlert(ALERT_CLASS_DANGER, LOGIN_DETAILS); }); } else { $rootScope.$broadcast('userNameExistenceCheckComplete'); } } }]); /* concatenated from client/src/app/js/ramblersWalksServices.js */ angular.module('ekwgApp') .factory('RamblersHttpService', ["$q", "$http", function ($q, $http) { function call(serviceCallType, method, url, data, params) { var deferredTask = $q.defer(); deferredTask.notify(serviceCallType); $http({ method: method, data: data, params: params, url: url }).then(function (response) { var responseData = response.data; if (responseData.error) { deferredTask.reject(response); } else { deferredTask.notify(responseData.information); deferredTask.resolve(responseData) } }).catch(function (response) { deferredTask.reject(response); }); return deferredTask.promise; } return { call: call } }]) .factory('RamblersWalksAndEventsService', ["$log", "$rootScope", "$http", "$q", "$filter", "DateUtils", "RamblersHttpService", "LoggedInMemberService", "CommitteeReferenceData", function ($log, $rootScope, $http, $q, $filter, DateUtils, RamblersHttpService, LoggedInMemberService, CommitteeReferenceData) { var logger = $log.getInstance('RamblersWalksAndEventsService'); $log.logLevels['RamblersWalksAndEventsService'] = $log.LEVEL.OFF; function uploadRamblersWalks(data) { return RamblersHttpService.call('Upload Ramblers walks', 'POST', 'walksAndEventsManager/uploadWalks', data); } function listRamblersWalks() { return RamblersHttpService.call('List Ramblers walks', 'GET', 'walksAndEventsManager/listWalks'); } var walkDescriptionPrefix = function () { return RamblersHttpService.call('Ramblers description Prefix', 'GET', 'walksAndEventsManager/walkDescriptionPrefix'); }; var walkBaseUrl = function () { return RamblersHttpService.call('Ramblers walk url', 'GET', 'walksAndEventsManager/walkBaseUrl'); }; function exportWalksFileName() { return 'walks-export-' + DateUtils.asMoment().format('DD-MMMM-YYYY-HH-mm') + '.csv' } function exportableWalks(walkExports) { return _.chain(walkExports) .filter(function (walkExport) { return walkExport.selected; }) .sortBy(function (walkExport) { return walkExport.walk.walkDate; }) .value(); } function exportWalks(walkExports, members) { return _(exportableWalks(walkExports)).pluck('walk').map(function (walk) { return walkToCsvRecord(walk, members) }); } function createWalksForExportPrompt(walks, members) { return listRamblersWalks() .then(updateWalksWithRamblersWalkData(walks)) .then(function (updatedWalks) { return returnWalksExport(updatedWalks, members); }); } function updateWalksWithRamblersWalkData(walks) { var unreferencedList = collectExistingRamblersIdsFrom(walks); logger.debug(unreferencedList.length, ' existing ramblers walk(s) found', unreferencedList); return function (ramblersWalksResponses) { var savePromises = []; _(ramblersWalksResponses.responseData).each(function (ramblersWalksResponse) { var foundWalk = _.find(walks, function (walk) { return DateUtils.asString(walk.walkDate, undefined, 'dddd, Do MMMM YYYY') === ramblersWalksResponse.ramblersWalkDate }); if (!foundWalk) { logger.debug('no match found for ramblersWalksResponse', ramblersWalksResponse); } else { unreferencedList = _.without(unreferencedList, ramblersWalksResponse.ramblersWalkId); if (foundWalk && foundWalk.ramblersWalkId !== ramblersWalksResponse.ramblersWalkId) { logger.debug('updating walk from', foundWalk.ramblersWalkId || 'empty', '->', ramblersWalksResponse.ramblersWalkId, 'on', $filter('displayDate')(foundWalk.walkDate)); foundWalk.ramblersWalkId = ramblersWalksResponse.ramblersWalkId; savePromises.push(foundWalk.$saveOrUpdate()) } else { logger.debug('no update required for walk', foundWalk.ramblersWalkId, foundWalk.walkDate, DateUtils.displayDay(foundWalk.walkDate)); } } }); if (unreferencedList.length > 0) { logger.debug('removing old ramblers walk(s)', unreferencedList, 'from existing walks'); _.chain(unreferencedList) .each(function (ramblersWalkId) { var walk = _.findWhere(walks, {ramblersWalkId: ramblersWalkId}); if (walk) { logger.debug('removing ramblers walk', walk.ramblersWalkId, 'from walk on', $filter('displayDate')(walk.walkDate)); delete walk.ramblersWalkId; savePromises.push(walk.$saveOrUpdate()) } }).value(); } return $q.all(savePromises).then(function () { return walks; }); } } function collectExistingRamblersIdsFrom(walks) { return _.chain(walks) .filter(function (walk) { return walk.ramblersWalkId; }) .map(function (walk) { return walk.ramblersWalkId; }) .value(); } function returnWalksExport(walks, members) { var todayValue = DateUtils.momentNowNoTime().valueOf(); return _.chain(walks) .filter(function (walk) { return (walk.walkDate >= todayValue) && walk.briefDescriptionAndStartPoint; }) .sortBy(function (walk) { return walk.walkDate; }) .map(function (walk) { return validateWalk(walk, members); }) .value(); } function uploadToRamblers(walkExports, members, notify) { notify.setBusy(); logger.debug('sourceData', walkExports); var deleteWalks = _.chain(exportableWalks(walkExports)).pluck('walk') .filter(function (walk) { return walk.ramblersWalkId; }).map(function (walk) { return walk.ramblersWalkId; }).value(); let rows = exportWalks(walkExports, members); let fileName = exportWalksFileName(); var data = { headings: exportColumnHeadings(), rows: rows, fileName: fileName, deleteWalks: deleteWalks, ramblersUser: LoggedInMemberService.loggedInMember().firstName }; logger.debug('exporting', data); notify.warning({ title: 'Ramblers walks upload', message: 'Uploading ' + rows.length + ' walk(s) to Ramblers...' }); return uploadRamblersWalks(data) .then(function (response) { notify.warning({ title: 'Ramblers walks upload', message: 'Upload of ' + rows.length + ' walk(s) to Ramblers has been submitted. Monitor the Walk upload audit tab for progress' }); logger.debug('success response data', response); notify.clearBusy(); return fileName; }) .catch(function (response) { logger.debug('error response data', response); notify.error({ title: 'Ramblers walks upload failed', message: response }); notify.clearBusy(); }); } function validateWalk(walk, members) { var walkValidations = []; if (_.isEmpty(walk)) { walkValidations.push('walk does not exist'); } else { if (_.isEmpty(walkTitle(walk))) walkValidations.push('title is missing'); if (_.isEmpty(walkDistanceMiles(walk))) walkValidations.push('distance is missing'); if (_.isEmpty(walk.startTime)) walkValidations.push('start time is missing'); if (walkStartTime(walk) === 'Invalid date') walkValidations.push('start time [' + walk.startTime + '] is invalid'); if (_.isEmpty(walk.grade)) walkValidations.push('grade is missing'); if (_.isEmpty(walk.longerDescription)) walkValidations.push('description is missing'); if (_.isEmpty(walk.postcode) && _.isEmpty(walk.gridReference)) walkValidations.push('both postcode and grid reference are missing'); if (_.isEmpty(walk.contactId)) { var contactIdMessage = LoggedInMemberService.allowWalkAdminEdits() ? 'this can be supplied for this walk on Walk Leader tab' : 'this will need to be setup for you by ' + CommitteeReferenceData.contactUsField('walks', 'fullName'); walkValidations.push('walk leader has no Ramblers contact Id setup on their member record (' + contactIdMessage + ')'); } if (_.isEmpty(walk.displayName) && _.isEmpty(walk.displayName)) walkValidations.push('displayName for walk leader is missing'); } return { walk: walk, walkValidations: walkValidations, publishedOnRamblers: walk && !_.isEmpty(walk.ramblersWalkId), selected: walk && walkValidations.length === 0 && _.isEmpty(walk.ramblersWalkId) } } var nearestTown = function (walk) { return walk.nearestTown ? 'Nearest Town is ' + walk.nearestTown : ''; }; function walkTitle(walk) { var walkDescription = []; if (walk.briefDescriptionAndStartPoint) walkDescription.push(walk.briefDescriptionAndStartPoint); return _.chain(walkDescription).map(replaceSpecialCharacters).value().join('. '); } function walkDescription(walk) { return replaceSpecialCharacters(walk.longerDescription); } function walkType(walk) { return walk.walkType || "Circular"; } function asString(value) { return value ? value : ''; } function contactDisplayName(walk) { return walk.displayName ? replaceSpecialCharacters(_.first(walk.displayName.split(' '))) : ''; } function contactIdLookup(walk, members) { if (walk.contactId) { return walk.contactId; } else { var member = _(members).find(function (member) { return member.$id() === walk.walkLeaderMemberId; }); var returnValue = member && member.contactId; logger.debug('contactId: for walkLeaderMemberId', walk.walkLeaderMemberId, '->', returnValue); return returnValue; } } function replaceSpecialCharacters(value) { return value ? value .replace("’", "'") .replace("é", "e") .replace("’", "'") .replace('…', '…') .replace('–', '–') .replace('’', '’') .replace('“', '“') : ''; } function walkDistanceMiles(walk) { return walk.distance ? String(parseFloat(walk.distance).toFixed(1)) : ''; } function walkStartTime(walk) { return walk.startTime ? DateUtils.asString(walk.startTime, 'HH mm', 'HH:mm') : ''; } function walkGridReference(walk) { return walk.gridReference ? walk.gridReference : ''; } function walkPostcode(walk) { return walk.gridReference ? '' : walk.postcode ? walk.postcode : ''; } function walkDate(walk) { return DateUtils.asString(walk.walkDate, undefined, 'DD-MM-YYYY'); } function exportColumnHeadings() { return [ "Date", "Title", "Description", "Linear or Circular", "Starting postcode", "Starting gridref", "Starting location details", "Show exact starting point", "Start time", "Show exact meeting point?", "Meeting time", "Restriction", "Difficulty", "Local walk grade", "Distance miles", "Contact id", "Contact display name" ]; } function walkToCsvRecord(walk, members) { return { "Date": walkDate(walk), "Title": walkTitle(walk), "Description": walkDescription(walk), "Linear or Circular": walkType(walk), "Starting postcode": walkPostcode(walk), "Starting gridref": walkGridReference(walk), "Starting location details": nearestTown(walk), "Show exact starting point": "Yes", "Start time": walkStartTime(walk), "Show exact meeting point?": "Yes", "Meeting time": walkStartTime(walk), "Restriction": "Public", "Difficulty": asString(walk.grade), "Local walk grade": asString(walk.grade), "Distance miles": walkDistanceMiles(walk), "Contact id": contactIdLookup(walk, members), "Contact display name": contactDisplayName(walk) }; } return { uploadToRamblers: uploadToRamblers, validateWalk: validateWalk, walkDescriptionPrefix: walkDescriptionPrefix, walkBaseUrl: walkBaseUrl, exportWalksFileName: exportWalksFileName, createWalksForExportPrompt: createWalksForExportPrompt, exportWalks: exportWalks, exportableWalks: exportableWalks, exportColumnHeadings: exportColumnHeadings } }] ); /* concatenated from client/src/app/js/resetPasswordController.js */ angular.module("ekwgApp") .controller("ResetPasswordController", ["$q", "$log", "$scope", "AuthenticationModalsService", "ValidationUtils", "LoggedInMemberService", "URLService", "Notifier", "userName", "message", "close", function ($q, $log, $scope, AuthenticationModalsService, ValidationUtils, LoggedInMemberService, URLService, Notifier, userName, message, close) { var logger = $log.getInstance('ResetPasswordController'); $log.logLevels['ResetPasswordController'] = $log.LEVEL.OFF; $scope.notify = {}; $scope.memberCredentials = {userName: userName}; var notify = Notifier($scope.notify); if (message) { notify.progress({ title: "Reset password", message: message }); } $scope.actions = { submittable: function () { var newPasswordPopulated = ValidationUtils.fieldPopulated($scope.memberCredentials, "newPassword"); var newPasswordConfirmPopulated = ValidationUtils.fieldPopulated($scope.memberCredentials, "newPasswordConfirm"); logger.info("notSubmittable: newPasswordConfirmPopulated", newPasswordConfirmPopulated, "newPasswordPopulated", newPasswordPopulated); return newPasswordPopulated && newPasswordConfirmPopulated; }, close: function () { close() }, resetPassword: function () { notify.showContactUs(false); notify.setBusy(); notify.progress({ busy: true, title: "Reset password", message: "Attempting reset of password for " + $scope.memberCredentials.userName }); LoggedInMemberService.resetPassword($scope.memberCredentials.userName, $scope.memberCredentials.newPassword, $scope.memberCredentials.newPasswordConfirm).then(function () { var loginResponse = LoggedInMemberService.loginResponse(); if (LoggedInMemberService.memberLoggedIn()) { notify.hide(); close(); if (!LoggedInMemberService.loggedInMember().profileSettingsConfirmed) { return URLService.navigateTo("mailing-preferences"); } return true; } else { notify.showContactUs(true); notify.error({ title: "Reset password failed", message: loginResponse.alertMessage }); } return true; }); } } }] ); /* concatenated from client/src/app/js/resetPasswordFailedController.js */ angular.module('ekwgApp') .controller('ResetPasswordFailedController', ["$log", "$scope", "URLService", "Notifier", "CommitteeReferenceData", "close", function ($log, $scope, URLService, Notifier, CommitteeReferenceData, close) { var logger = $log.getInstance('ResetPasswordFailedController'); $log.logLevels['MemberAdminController'] = $log.LEVEL.OFF; $scope.notify = {}; var notify = Notifier($scope.notify); logger.info("CommitteeReferenceData:", CommitteeReferenceData.ready); notify.showContactUs(true); notify.error({ continue: true, title: "Reset password failed", message: "The password reset link you followed has either expired or is invalid. Click Restart Forgot Password to try again" }); $scope.actions = { close: function () { close() }, forgotPassword: function () { URLService.navigateTo("forgot-password"); }, } }]); /* concatenated from client/src/app/js/services.js */ angular.module('ekwgApp') .factory('DateUtils', ["$log", function ($log) { var logger = $log.getInstance('DateUtils'); $log.logLevels['DateUtils'] = $log.LEVEL.OFF; var formats = { displayDateAndTime: 'ddd DD-MMM-YYYY, h:mm:ss a', displayDateTh: 'MMMM Do YYYY', displayDate: 'ddd DD-MMM-YYYY', displayDay: 'dddd MMMM D, YYYY', ddmmyyyyWithSlashes: 'DD/MM/YYYY', yyyymmdd: 'YYYYMMDD' }; function isDate(value) { return value && asMoment(value).isValid(); } function asMoment(dateValue, inputFormat) { return moment(dateValue, inputFormat).tz("Europe/London"); } function momentNow() { return asMoment(); } function asString(dateValue, inputFormat, outputFormat) { var returnValue = dateValue ? asMoment(dateValue, inputFormat).format(outputFormat) : undefined; logger.debug('asString: dateValue ->', dateValue, 'inputFormat ->', inputFormat, 'outputFormat ->', outputFormat, 'returnValue ->', returnValue); return returnValue; } function asValue(dateValue, inputFormat) { return asMoment(dateValue, inputFormat).valueOf(); } function nowAsValue() { return asMoment(undefined, undefined).valueOf(); } function mailchimpDate(dateValue) { return asString(dateValue, undefined, formats.ddmmyyyyWithSlashes); } function displayDateAndTime(dateValue) { return asString(dateValue, undefined, formats.displayDateAndTime); } function displayDate(dateValue) { return asString(dateValue, undefined, formats.displayDate); } function displayDay(dateValue) { return asString(dateValue, undefined, formats.displayDay); } function asValueNoTime(dateValue, inputFormat) { var returnValue = asMoment(dateValue, inputFormat).startOf('day').valueOf(); logger.debug('asValueNoTime: dateValue ->', dateValue, 'returnValue ->', returnValue, '->', displayDateAndTime(returnValue)); return returnValue; } function currentMemberBulkLoadDisplayDate() { return asString(momentNowNoTime().startOf('month'), undefined, formats.yyyymmdd); } function momentNowNoTime() { return asMoment().startOf('day'); } function convertDateFieldInObject(object, field) { var inputValue = object[field]; object[field] = convertDateField(inputValue); return object; } function convertDateField(inputValue) { if (inputValue) { var dateValue = asValueNoTime(inputValue); if (dateValue !== inputValue) { logger.debug('Converting date from', inputValue, '(' + displayDateAndTime(inputValue) + ') to', dateValue, '(' + displayDateAndTime(dateValue) + ')'); return dateValue; } else { logger.debug(inputValue, inputValue, 'is already in correct format'); return inputValue; } } else { logger.debug(inputValue, 'is not a date - no conversion'); return inputValue; } } return { formats: formats, displayDateAndTime: displayDateAndTime, displayDay: displayDay, displayDate: displayDate, mailchimpDate: mailchimpDate, convertDateFieldInObject: convertDateFieldInObject, convertDateField: convertDateField, isDate: isDate, asMoment: asMoment, nowAsValue: nowAsValue, momentNow: momentNow, momentNowNoTime: momentNowNoTime, asString: asString, asValue: asValue, asValueNoTime: asValueNoTime, currentMemberBulkLoadDisplayDate: currentMemberBulkLoadDisplayDate }; }]) .factory('DbUtils', ["$log", "DateUtils", "LoggedInMemberService", "AUDIT_CONFIG", function ($log, DateUtils, LoggedInMemberService, AUDIT_CONFIG) { var logger = $log.getInstance('DbUtilsLogger'); $log.logLevels['DbUtilsLogger'] = $log.LEVEL.OFF; function removeEmptyFieldsIn(obj) { _.each(obj, function (value, field) { logger.debug('processing', typeof(field), 'field', field, 'value', value); if (_.contains([null, undefined, ""], value)) { logger.debug('removing non-populated', typeof(field), 'field', field); delete obj[field]; } }); } function auditedSaveOrUpdate(resource, updateCallback, errorCallback) { if (AUDIT_CONFIG.auditSave) { if (resource.$id()) { resource.updatedDate = DateUtils.nowAsValue(); resource.updatedBy = LoggedInMemberService.loggedInMember().memberId; logger.debug('Auditing save of existing document', resource); } else { resource.createdDate = DateUtils.nowAsValue(); resource.createdBy = LoggedInMemberService.loggedInMember().memberId; logger.debug('Auditing save of new document', resource); } } else { resource = DateUtils.convertDateFieldInObject(resource, 'createdDate'); logger.debug('Not auditing save of', resource); } return resource.$saveOrUpdate(updateCallback, updateCallback, errorCallback || updateCallback, errorCallback || updateCallback) } return { removeEmptyFieldsIn: removeEmptyFieldsIn, auditedSaveOrUpdate: auditedSaveOrUpdate, } }]) .factory('FileUtils', ["$log", "DateUtils", "URLService", "ContentMetaDataService", function ($log, DateUtils, URLService, ContentMetaDataService) { var logger = $log.getInstance('FileUtils'); $log.logLevels['FileUtils'] = $log.LEVEL.OFF; function basename(path) { return path.split(/[\\/]/).pop() } function path(path) { return path.split(basename(path))[0]; } function attachmentTitle(resource, container, resourceName) { return (resource && _.isEmpty(getFileNameData(resource, container)) ? 'Attach' : 'Replace') + ' ' + resourceName; } function getFileNameData(resource, container) { return container ? resource[container].fileNameData : resource.fileNameData; } function resourceUrl(resource, container, metaDataPathSegment) { var fileNameData = getFileNameData(resource, container); return resource && fileNameData ? URLService.baseUrl() + ContentMetaDataService.baseUrl(metaDataPathSegment) + '/' + fileNameData.awsFileName : ''; } function previewUrl(memberResource) { if (memberResource) { switch (memberResource.resourceType) { case "email": return memberResource.data.campaign.archive_url_long; case "file": return memberResource.data.campaign.archive_url_long; } } var fileNameData = getFileNameData(resource, container); return resource && fileNameData ? URLService.baseUrl() + ContentMetaDataService.baseUrl(metaDataPathSegment) + '/' + fileNameData.awsFileName : ''; } function resourceTitle(resource) { logger.debug('resourceTitle:resource =>', resource); return resource ? (DateUtils.asString(resource.resourceDate, undefined, DateUtils.formats.displayDateTh) + ' - ' + (resource.data ? resource.data.fileNameData.title : "")) : ''; } function fileExtensionIs(fileName, extensions) { return _.contains(extensions, fileExtension(fileName)); } function fileExtension(fileName) { return fileName ? _.last(fileName.split('.')).toLowerCase() : ''; } function icon(resource, container) { var icon = 'icon-default.jpg'; var fileNameData = getFileNameData(resource, container); if (fileNameData && fileExtensionIs(fileNameData.awsFileName, ['doc', 'docx', 'jpg', 'pdf', 'ppt', 'png', 'txt', 'xls', 'xlsx'])) { icon = 'icon-' + fileExtension(fileNameData.awsFileName).substring(0, 3) + '.jpg'; } return "assets/images/ramblers/" + icon; } return { fileExtensionIs: fileExtensionIs, fileExtension: fileExtension, basename: basename, path: path, attachmentTitle: attachmentTitle, resourceUrl: resourceUrl, resourceTitle: resourceTitle, icon: icon } }]) .factory('StringUtils', ["DateUtils", "$filter", function (DateUtils, $filter) { function replaceAll(find, replace, str) { return str ? str.replace(new RegExp(find.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), replace) : str; } function stripLineBreaks(str, andTrim) { var replacedValue = str.replace(/(\r\n|\n|\r)/gm, ''); return andTrim && replacedValue ? replacedValue.trim() : replacedValue; } function left(str, chars) { return str.substr(0, chars); } function formatAudit(who, when, members) { var by = who ? 'by ' + $filter('memberIdToFullName')(who, members) : ''; return (who || when) ? by + (who && when ? ' on ' : '') + DateUtils.displayDateAndTime(when) : '(not audited)'; } return { left: left, replaceAll: replaceAll, stripLineBreaks: stripLineBreaks, formatAudit: formatAudit } }]).factory('ValidationUtils', function () { function fieldPopulated(object, path) { return (_.property(path)(object) || "").length > 0; } return { fieldPopulated: fieldPopulated, } }) .factory('NumberUtils', ["$log", function ($log) { var logger = $log.getInstance('NumberUtils'); $log.logLevels['NumberUtils'] = $log.LEVEL.OFF; function sumValues(items, fieldName) { if (!items) return 0; return _.chain(items).pluck(fieldName).reduce(function (memo, num) { return memo + asNumber(num); }, 0).value(); } function generateUid() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); } function asNumber(numberString, decimalPlaces) { if (!numberString) return 0; var isNumber = typeof numberString === 'number'; if (isNumber && !decimalPlaces) return numberString; var number = isNumber ? numberString : parseFloat(numberString.replace(/[^\d\.\-]/g, "")); if (isNaN(number)) return 0; var returnValue = (decimalPlaces) ? (parseFloat(number).toFixed(decimalPlaces)) / 1 : number; logger.debug('asNumber:', numberString, decimalPlaces, '->', returnValue); return returnValue; } return { asNumber: asNumber, sumValues: sumValues, generateUid: generateUid }; }]) .factory('ContentMetaData', ["$mongolabResourceHttp", function ($mongolabResourceHttp) { return $mongolabResourceHttp('contentMetaData'); }]) .factory('ConfigData', ["$mongolabResourceHttp", function ($mongolabResourceHttp) { return $mongolabResourceHttp('config'); }]) .factory('Config', ["$log", "ConfigData", "ErrorMessageService", function ($log, ConfigData, ErrorMessageService) { var logger = $log.getInstance('Config'); $log.logLevels['Config'] = $log.LEVEL.OFF; function getConfig(key, defaultOnEmpty) { logger.debug('getConfig:', key, 'defaultOnEmpty:', defaultOnEmpty); var queryObject = {}; queryObject[key] = {$exists: true}; return ConfigData.query(queryObject, {limit: 1}) .then(function (results) { if (results && results.length > 0) { return results[0]; } else { queryObject[key] = {}; return new ConfigData(defaultOnEmpty || queryObject); } }, function (response) { throw new Error('Query of ' + key + ' config failed: ' + response); }); } function saveConfig(key, config, saveCallback, errorSaveCallback) { logger.debug('saveConfig:', key); if (_.has(config, key)) { return config.$saveOrUpdate(saveCallback, saveCallback, errorSaveCallback || saveCallback, errorSaveCallback || saveCallback); } else { throw new Error('Attempt to save ' + ErrorMessageService.stringify(key) + ' config when ' + ErrorMessageService.stringify(key) + ' parent key not present in data: ' + ErrorMessageService.stringify(config)); } } return { getConfig: getConfig, saveConfig: saveConfig } }]) .factory('ExpenseClaimsService', ["$mongolabResourceHttp", function ($mongolabResourceHttp) { return $mongolabResourceHttp('expenseClaims'); }]) .factory('RamblersUploadAudit', ["$mongolabResourceHttp", function ($mongolabResourceHttp) { return $mongolabResourceHttp('ramblersUploadAudit'); }]) .factory('ErrorTransformerService', ["ErrorMessageService", function (ErrorMessageService) { function transform(errorResponse) { var message = ErrorMessageService.stringify(errorResponse); var duplicate = s.include(errorResponse, 'duplicate'); if (duplicate) { message = 'Duplicate data was detected. A member record must have a unique Contact Email, Display Name, Ramblers Membership Number and combination of First Name, Last Name and Alias. Please amend the current member and try again.'; } return {duplicate: duplicate, message: message} } return {transform: transform} }]) .factory('ErrorMessageService', function () { function stringify(message) { return _.isObject(message) ? JSON.stringify(message, censor(message)) : message; } function censor(censor) { var i = 0; return function (key, value) { if (i !== 0 && typeof(censor) === 'object' && typeof(value) === 'object' && censor === value) return '[Circular]'; if (i >= 29) // seems to be a hard maximum of 30 serialized objects? return '[Unknown]'; ++i; // so we know we aren't using the original object anymore return value; } } return { stringify: stringify } }); /* concatenated from client/src/app/js/siteEditActions.js */ angular.module('ekwgApp') .component('siteEditActions', { templateUrl: 'partials/components/site-edit.html', controller: ["$log", "SiteEditService", function ($log, SiteEditService){ var logger = $log.getInstance('SiteEditActionsController'); $log.logLevels['SiteEditActionsController'] = $log.LEVEL.OFF; var ctrl = this; logger.info("initialised with SiteEditService.active()", SiteEditService.active()); ctrl.userEdits = {preview: true, saveInProgress: false, revertInProgress: false}; ctrl.editSiteActive = function () { return SiteEditService.active() ? "active" : ""; }; ctrl.editSiteCaption = function () { return SiteEditService.active() ? "editing site" : "edit site"; }; ctrl.toggleEditSite = function () { SiteEditService.toggle(); }; }], bindings: { name: '@', description: '@', } }); /* concatenated from client/src/app/js/siteEditService.js */ angular.module('ekwgApp') .factory('SiteEditService', ["$log", "$cookieStore", "$rootScope", function ($log, $cookieStore, $rootScope) { var logger = $log.getInstance('SiteEditService'); $log.logLevels['SiteEditService'] = $log.LEVEL.OFF; function active() { var active = Boolean($cookieStore.get("editSite")); logger.debug("active:", active); return active; } function toggle() { var priorState = active(); var newState = !priorState; logger.debug("toggle:priorState", priorState, "newState", newState); $cookieStore.put("editSite", newState); return $rootScope.$broadcast("editSite", newState); } return { active: active, toggle: toggle } }]); /* concatenated from client/src/app/js/socialEventNotifications.js */ angular.module('ekwgApp') .controller('SocialEventNotificationsController', ["MAILCHIMP_APP_CONSTANTS", "$window", "$log", "$sce", "$timeout", "$templateRequest", "$compile", "$q", "$rootScope", "$scope", "$filter", "$routeParams", "$location", "URLService", "DateUtils", "NumberUtils", "LoggedInMemberService", "MemberService", "ContentMetaDataService", "CommitteeFileService", "MailchimpSegmentService", "MailchimpCampaignService", "MailchimpConfig", "Notifier", "CommitteeReferenceData", "socialEvent", "close", function (MAILCHIMP_APP_CONSTANTS, $window, $log, $sce, $timeout, $templateRequest, $compile, $q, $rootScope, $scope, $filter, $routeParams, $location, URLService, DateUtils, NumberUtils, LoggedInMemberService, MemberService, ContentMetaDataService, CommitteeFileService, MailchimpSegmentService, MailchimpCampaignService, MailchimpConfig, Notifier, CommitteeReferenceData, socialEvent, close) { var logger = $log.getInstance('SocialEventNotificationsController'); $log.logLevels['SocialEventNotificationsController'] = $log.LEVEL.OFF; $scope.notify = {}; var notify = Notifier($scope.notify); notify.setBusy(); logger.debug('created with social event', socialEvent); $scope.attachmentBaseUrl = ContentMetaDataService.baseUrl('socialEvents'); $scope.destinationType = ''; $scope.members = []; $scope.selectableRecipients = []; $scope.committeeFiles = []; $scope.alertMessages = []; $scope.allowConfirmDelete = false; $scope.latestYearOpen = true; $scope.roles = {signoff: [], replyTo: []}; $scope.showAlertMessage = function () { return ($scope.notify.alert.class === 'alert-danger') || $scope.userEdits.sendInProgress; }; function initialiseNotification(socialEvent) { if (socialEvent) { $scope.socialEvent = socialEvent; onFirstNotificationOnly(); forEveryNotification(); } else { logger.error('no socialEvent - problem!'); } function onFirstNotificationOnly() { if (!$scope.socialEvent.notification) { $scope.socialEvent.notification = { destinationType: 'all-ekwg-social', recipients: [], addresseeType: 'Hi *|FNAME|*,', items: { title: {include: true}, notificationText: {include: true, value: ''}, description: {include: true}, attendees: {include: socialEvent.attendees.length > 0}, attachment: {include: socialEvent.attachment}, replyTo: { include: $scope.socialEvent.displayName, value: $scope.socialEvent.displayName ? 'organiser' : 'social' }, signoffText: { include: true, value: 'If you have any questions about the above, please don\'t hesitate to contact me.\n\nBest regards,' } } }; logger.debug('onFirstNotificationOnly - creating $scope.socialEvent.notification ->', $scope.socialEvent.notification); } } function forEveryNotification() { $scope.socialEvent.notification.items.signoffAs = { include: true, value: loggedOnRole().type || 'social' }; logger.debug('forEveryNotification - $scope.socialEvent.notification.signoffAs ->', $scope.socialEvent.notification.signoffAs); } } function loggedOnRole() { var memberId = LoggedInMemberService.loggedInMember().memberId; var loggedOnRoleData = _(CommitteeReferenceData.contactUsRolesAsArray()).find(function (role) { return role.memberId === memberId }); logger.debug('loggedOnRole for', memberId, '->', loggedOnRoleData); return loggedOnRoleData || {}; } function roleForType(type) { var role = _($scope.roles.replyTo).find(function (role) { return role.type === type; }); logger.debug('roleForType for', type, '->', role); return role; } function initialiseRoles() { $scope.roles.signoff = CommitteeReferenceData.contactUsRolesAsArray(); $scope.roles.replyTo = _.clone($scope.roles.signoff); if ($scope.socialEvent.eventContactMemberId) { $scope.roles.replyTo.unshift({ type: 'organiser', fullName: $scope.socialEvent.displayName, memberId: $scope.socialEvent.eventContactMemberId, description: 'Organiser (' + $scope.socialEvent.displayName + ')', email: $scope.socialEvent.contactEmail }); } logger.debug('initialiseRoles -> $scope.roles ->', $scope.roles); } $scope.formattedText = function () { return $filter('lineFeedsToBreaks')($scope.socialEvent.notification.items.notificationText.value); }; $scope.attachmentTitle = function (socialEvent) { return socialEvent && socialEvent.attachment ? (socialEvent.attachment.title || socialEvent.attachmentTitle || 'Attachment: ' + socialEvent.attachment.originalFileName) : ''; }; $scope.attachmentUrl = function (socialEvent) { return socialEvent && socialEvent.attachment ? URLService.baseUrl() + $scope.attachmentBaseUrl + '/' + socialEvent.attachment.awsFileName : ''; }; $scope.editAllSocialRecipients = function () { $scope.socialEvent.notification.destinationType = 'custom'; $scope.socialEvent.notification.recipients = $scope.userEdits.socialList(); }; $scope.editAttendeeRecipients = function () { $scope.socialEvent.notification.destinationType = 'custom'; $scope.socialEvent.notification.recipients = $scope.socialEvent.attendees; }; $scope.clearRecipients = function () { $scope.socialEvent.notification.recipients = []; }; $scope.formattedSignoffText = function () { return $filter('lineFeedsToBreaks')($scope.socialEvent.notification.items.signoffText.value); }; $scope.attendeeList = function () { return _($scope.socialEvent.notification && $scope.socialEvent.attendees) .sortBy(function (attendee) { return attendee.text; }).map(function (attendee) { return attendee.text; }).join(', '); }; $scope.memberGrouping = function (member) { return member.memberGrouping; }; function toSelectMember(member) { var memberGrouping; var order; if (member.socialMember && member.mailchimpLists.socialEvents.subscribed) { memberGrouping = 'Subscribed to social emails'; order = 0; } else if (member.socialMember && !member.mailchimpLists.socialEvents.subscribed) { memberGrouping = 'Not subscribed to social emails'; order = 1; } else if (!member.socialMember) { memberGrouping = 'Not a social member'; order = 2; } else { memberGrouping = 'Unexpected state'; order = 3; } return { id: member.$id(), order: order, memberGrouping: memberGrouping, text: $filter('fullNameWithAlias')(member) }; } function refreshMembers() { if (LoggedInMemberService.memberLoggedIn()) { MemberService.allLimitedFields(MemberService.filterFor.GROUP_MEMBERS).then(function (members) { $scope.members = members; logger.debug('refreshMembers -> populated ->', $scope.members.length, 'members'); $scope.selectableRecipients = _.chain(members) .map(toSelectMember) .sortBy(function (member) { return member.order + member.text }) .value(); logger.debug('refreshMembers -> populated ->', $scope.selectableRecipients.length, 'selectableRecipients'); notify.clearBusy(); }); } } $scope.contactUs = { ready: function () { return CommitteeReferenceData.ready; } }; $scope.userEdits = { sendInProgress: false, cancelFlow: false, socialList: function () { return _.chain($scope.members) .filter(MemberService.filterFor.SOCIAL_MEMBERS_SUBSCRIBED) .map(toSelectMember).value(); }, replyToRole: function () { return _($scope.roles.replyTo).find(function (role) { return role.type === $scope.socialEvent.notification.items.replyTo.value; }); }, notReady: function () { return $scope.members.length === 0 || $scope.userEdits.sendInProgress; } }; $scope.cancelSendNotification = function () { close(); $('#social-event-dialog').modal('show'); }; $scope.completeInMailchimp = function () { notify.warning({ title: 'Complete in Mailchimp', message: 'You can close this dialog now as the message was presumably completed and sent in Mailchimp' }); $scope.confirmSendNotification(true); }; $scope.confirmSendNotification = function (dontSend) { notify.setBusy(); var campaignName = $scope.socialEvent.briefDescription; logger.debug('sendSocialNotification:notification->', $scope.socialEvent.notification); notify.progress({title: campaignName, message: 'preparing and sending notification'}); $scope.userEdits.sendInProgress = true; $scope.userEdits.cancelFlow = false; function getTemplate() { return $templateRequest($sce.getTrustedResourceUrl('partials/socialEvents/social-notification.html')) } return $q.when(createOrSaveMailchimpSegment()) .then(getTemplate) .then(renderTemplateContent) .then(populateContentSections) .then(sendEmailCampaign) .then(saveSocialEvent) .then(notifyEmailSendComplete) .catch(handleError); function handleError(errorResponse) { $scope.userEdits.sendInProgress = false; notify.error({ title: 'Your notification could not be sent', message: (errorResponse.message || errorResponse) + (errorResponse.error ? ('. Error was: ' + JSON.stringify(errorResponse.error)) : '') }); notify.clearBusy(); } function renderTemplateContent(templateData) { var task = $q.defer(); var templateFunction = $compile(templateData); var templateElement = templateFunction($scope); $timeout(function () { $scope.$digest(); task.resolve(templateElement.html()); }); return task.promise; } function populateContentSections(notificationText) { logger.debug('populateContentSections -> notificationText', notificationText); return { sections: { notification_text: notificationText } }; } function writeSegmentResponseDataToEvent(segmentResponse) { $scope.socialEvent.mailchimp = { segmentId: segmentResponse.segment.id }; if (segmentResponse.members) $scope.socialEvent.mailchimp.members = segmentResponse.members; } function createOrSaveMailchimpSegment() { var members = segmentMembers(); if (members.length > 0) { return MailchimpSegmentService.saveSegment('socialEvents', $scope.socialEvent.mailchimp, members, MailchimpSegmentService.formatSegmentName($scope.socialEvent.briefDescription), $scope.members) .then(writeSegmentResponseDataToEvent) .catch(handleError); } else { logger.debug('not saving segment data as destination type is whole mailing list ->', $scope.socialEvent.notification.destinationType); return true; } } function segmentMembers() { switch ($scope.socialEvent.notification.destinationType) { case 'attendees': return $scope.socialEvent.attendees; case 'custom': return $scope.socialEvent.notification.recipients; default: return []; } } function sendEmailCampaign(contentSections) { var replyToRole = roleForType($scope.socialEvent.notification.items.replyTo.value || 'social'); var otherOptions = ($scope.socialEvent.notification.items.replyTo.include && replyToRole.fullName && replyToRole.email) ? { from_name: replyToRole.fullName, from_email: replyToRole.email } : {}; notify.progress(dontSend ? ('Preparing to complete ' + campaignName + ' in Mailchimp') : ('Sending ' + campaignName)); logger.debug('Sending ' + campaignName, 'with otherOptions', otherOptions); return MailchimpConfig.getConfig() .then(function (config) { var campaignId = config.mailchimp.campaigns.socialEvents.campaignId; switch ($scope.socialEvent.notification.destinationType) { case 'all-ekwg-social': logger.debug('about to replicateAndSendWithOptions to all-ekwg-social with campaignName', campaignName, 'campaign Id', campaignId); return MailchimpCampaignService.replicateAndSendWithOptions({ campaignId: campaignId, campaignName: campaignName, contentSections: contentSections, otherSegmentOptions: otherOptions, dontSend: dontSend }).then(openInMailchimpIf(dontSend)); default: if (!$scope.socialEvent.mailchimp) notify.warning('Cant send campaign due to previous request failing. This could be due to network problems - please try this again'); var segmentId = $scope.socialEvent.mailchimp.segmentId; logger.debug('about to replicateAndSendWithOptions to social with campaignName', campaignName, 'campaign Id', campaignId, 'segmentId', segmentId); return MailchimpCampaignService.replicateAndSendWithOptions({ campaignId: campaignId, campaignName: campaignName, contentSections: contentSections, segmentId: segmentId, otherSegmentOptions: otherOptions, dontSend: dontSend }).then(openInMailchimpIf(dontSend)); } }) } function openInMailchimpIf(dontSend) { return function (replicateCampaignResponse) { logger.debug('openInMailchimpIf:replicateCampaignResponse', replicateCampaignResponse, 'dontSend', dontSend); if (dontSend) { return $window.open(MAILCHIMP_APP_CONSTANTS.apiServer + "/campaigns/wizard/neapolitan?id=" + replicateCampaignResponse.web_id, '_blank'); } else { return true; } } } function saveSocialEvent() { return $scope.socialEvent.$saveOrUpdate(); } function notifyEmailSendComplete() { notify.success('Sending of ' + campaignName + ' was successful.', false); $scope.userEdits.sendInProgress = false; if (!$scope.userEdits.cancelFlow) { close(); } notify.clearBusy(); } }; refreshMembers(); initialiseNotification(socialEvent); initialiseRoles(CommitteeReferenceData); }] ); /* concatenated from client/src/app/js/socialEvents.js */ angular.module('ekwgApp') .factory('SocialEventsService', ["$mongolabResourceHttp", function ($mongolabResourceHttp) { return $mongolabResourceHttp('socialEvents'); }]) .factory('SocialEventAttendeeService', ["$mongolabResourceHttp", function ($mongolabResourceHttp) { return $mongolabResourceHttp('socialEventAttendees'); }]) .controller('SocialEventsController', ["$routeParams", "$log", "$q", "$scope", "$filter", "URLService", "Upload", "SocialEventsService", "SiteEditService", "SocialEventAttendeeService", "LoggedInMemberService", "MemberService", "AWSConfig", "ContentMetaDataService", "DateUtils", "MailchimpSegmentService", "ClipboardService", "Notifier", "EKWGFileUpload", "CommitteeReferenceData", "ModalService", function ($routeParams, $log, $q, $scope, $filter, URLService, Upload, SocialEventsService, SiteEditService, SocialEventAttendeeService, LoggedInMemberService, MemberService, AWSConfig, ContentMetaDataService, DateUtils, MailchimpSegmentService, ClipboardService, Notifier, EKWGFileUpload, CommitteeReferenceData, ModalService) { $scope.userEdits = { copyToClipboard: ClipboardService.copyToClipboard, longerDescriptionPreview: true, socialEventLink: function (socialEvent) { return socialEvent && socialEvent.$id() ? URLService.notificationHref({ type: "socialEvent", area: "social", id: socialEvent.$id() }) : undefined; } }; $scope.previewLongerDescription = function () { logger.debug('previewLongerDescription'); $scope.userEdits.longerDescriptionPreview = true; }; $scope.editLongerDescription = function () { logger.debug('editLongerDescription'); $scope.userEdits.longerDescriptionPreview = false; }; $scope.contactUs = { ready: function () { return CommitteeReferenceData.ready; } }; var logger = $log.getInstance('SocialEventsController'); $log.logLevels['SocialEventsController'] = $log.LEVEL.OFF; var notify = Notifier($scope); $scope.attachmentBaseUrl = ContentMetaDataService.baseUrl('socialEvents'); $scope.selectMembers = []; $scope.display = {attendees: []}; $scope.socialEventsDetailProgrammeOpen = true; $scope.socialEventsBriefProgrammeOpen = true; $scope.socialEventsInformationOpen = true; $scope.todayValue = DateUtils.momentNowNoTime().valueOf(); applyAllowEdits('controllerInitialisation'); $scope.eventDateCalendar = { open: function ($event) { $event.preventDefault(); $event.stopPropagation(); $scope.eventDateCalendar.opened = true; } }; $scope.$on('memberLoginComplete', function () { applyAllowEdits('memberLoginComplete'); refreshMembers(); refreshSocialEvents(); }); $scope.$on('memberLogoutComplete', function () { applyAllowEdits('memberLogoutComplete'); }); $scope.$on('editSite', function () { applyAllowEdits('editSite'); }); $scope.addSocialEvent = function () { showSocialEventDialog(new SocialEventsService({eventDate: $scope.todayValue, attendees: []}), 'Add New'); }; $scope.viewSocialEvent = function (socialEvent) { showSocialEventDialog(socialEvent, 'View'); }; $scope.editSocialEvent = function (socialEvent) { showSocialEventDialog(socialEvent, 'Edit Existing'); }; $scope.deleteSocialEventDetails = function () { $scope.allowDelete = false; $scope.allowConfirmDelete = true; }; $scope.cancelSocialEventDetails = function () { hideSocialEventDialogAndRefreshSocialEvents(); }; $scope.saveSocialEventDetails = function () { $q.when(notify.progress({title: 'Save in progress', message: 'Saving social event'}, true)) .then(prepareToSave, notify.error, notify.progress) .then(saveSocialEvent, notify.error, notify.progress) .then(notify.clearBusy, notify.error, notify.progress) .catch(notify.error); }; function prepareToSave() { DateUtils.convertDateFieldInObject($scope.currentSocialEvent, 'eventDate'); } function saveSocialEvent() { return $scope.currentSocialEvent.$saveOrUpdate(hideSocialEventDialogAndRefreshSocialEvents, hideSocialEventDialogAndRefreshSocialEvents); } $scope.confirmDeleteSocialEventDetails = function () { $q.when(notify.progress('Deleting social event', true)) .then(deleteMailchimpSegment, notify.error, notify.progress) .then(removeSocialEventHideSocialEventDialogAndRefreshSocialEvents, notify.error, notify.progress) .then(notify.clearBusy, notify.error, notify.progress) .catch(notify.error); }; var deleteMailchimpSegment = function () { if ($scope.currentSocialEvent.mailchimp && $scope.currentSocialEvent.mailchimp.segmentId) { return MailchimpSegmentService.deleteSegment('socialEvents', $scope.currentSocialEvent.mailchimp.segmentId); } }; var removeSocialEventHideSocialEventDialogAndRefreshSocialEvents = function () { $scope.currentSocialEvent.$remove(hideSocialEventDialogAndRefreshSocialEvents) }; $scope.copyDetailsToNewSocialEvent = function () { var copiedSocialEvent = new SocialEventsService($scope.currentSocialEvent); delete copiedSocialEvent._id; delete copiedSocialEvent.mailchimp; DateUtils.convertDateFieldInObject(copiedSocialEvent, 'eventDate'); showSocialEventDialog(copiedSocialEvent, 'Copy Existing'); notify.success({ title: 'Existing social event copied!', message: 'Make changes here and save to create a new social event.' }); }; $scope.selectMemberContactDetails = function () { var socialEvent = $scope.currentSocialEvent; var memberId = socialEvent.eventContactMemberId; if (memberId === null) { delete socialEvent.eventContactMemberId; delete socialEvent.displayName; delete socialEvent.contactPhone; delete socialEvent.contactEmail; // console.log('deleted contact details from', socialEvent); } else { var selectedMember = _.find($scope.members, function (member) { return member.$id() === memberId; }); socialEvent.displayName = selectedMember.displayName; socialEvent.contactPhone = selectedMember.mobileNumber; socialEvent.contactEmail = selectedMember.email; // console.log('set contact details on', socialEvent); } }; $scope.dataQueryParameters = { query: '', selectType: '1', newestFirst: 'false' }; $scope.removeAttachment = function () { delete $scope.currentSocialEvent.attachment; delete $scope.currentSocialEvent.attachmentTitle; $scope.uploadedFile = undefined; }; $scope.resetMailchimpData = function () { delete $scope.currentSocialEvent.mailchimp; }; $scope.addOrReplaceAttachment = function () { $('#hidden-input').click(); }; $scope.attachmentTitle = function (socialEvent) { return socialEvent && socialEvent.attachment ? (socialEvent.attachment.title || socialEvent.attachmentTitle || 'Attachment: ' + socialEvent.attachment.originalFileName) : ''; }; $scope.attachmentUrl = function (socialEvent) { return socialEvent && socialEvent.attachment ? $scope.attachmentBaseUrl + '/' + socialEvent.attachment.awsFileName : ''; }; $scope.onFileSelect = function (file) { if (file) { $scope.uploadedFile = file; EKWGFileUpload.onFileSelect(file, notify, 'socialEvents').then(function (fileNameData) { $scope.currentSocialEvent.attachment = fileNameData; }); } }; function allowSummaryView() { return (LoggedInMemberService.allowSocialAdminEdits() || !LoggedInMemberService.allowSocialDetailView()); } function applyAllowEdits(event) { $scope.allowDelete = false; $scope.allowConfirmDelete = false; $scope.allowDetailView = LoggedInMemberService.allowSocialDetailView(); $scope.allowEdits = LoggedInMemberService.allowSocialAdminEdits(); $scope.allowCopy = LoggedInMemberService.allowSocialAdminEdits(); $scope.allowContentEdits = SiteEditService.active() && LoggedInMemberService.allowContentEdits(); $scope.allowSummaryView = allowSummaryView(); } $scope.showLoginTooltip = function () { return !LoggedInMemberService.memberLoggedIn(); }; $scope.login = function () { if (!LoggedInMemberService.memberLoggedIn()) { URLService.navigateTo("login"); } }; function showSocialEventDialog(socialEvent, socialEventEditMode) { $scope.uploadedFile = undefined; $scope.showAlert = false; $scope.allowConfirmDelete = false; if (!socialEvent.attendees) socialEvent.attendees = []; $scope.allowEdits = LoggedInMemberService.allowSocialAdminEdits(); var existingRecordEditEnabled = $scope.allowEdits && s.startsWith(socialEventEditMode, 'Edit'); $scope.allowCopy = existingRecordEditEnabled; $scope.allowDelete = existingRecordEditEnabled; $scope.socialEventEditMode = socialEventEditMode; $scope.currentSocialEvent = socialEvent; $('#social-event-dialog').modal('show'); } $scope.attendeeCaption = function () { return $scope.currentSocialEvent && $scope.currentSocialEvent.attendees.length + ($scope.currentSocialEvent.attendees.length === 1 ? ' member is attending' : ' members are attending'); }; $scope.attendeeList = function () { return _($scope.display.attendees) .sortBy(function (attendee) { return attendee.text; }).map(function (attendee) { return attendee.text; }).join(', '); }; function hideSocialEventDialogAndRefreshSocialEvents() { $('#social-event-dialog').modal('hide'); refreshSocialEvents(); } function refreshMembers() { if (LoggedInMemberService.memberLoggedIn()) { MemberService.allLimitedFields(MemberService.filterFor.SOCIAL_MEMBERS).then(function (members) { $scope.members = members; logger.debug('found', $scope.members.length, 'members'); $scope.selectMembers = _($scope.members).map(function (member) { return {id: member.$id(), text: $filter('fullNameWithAlias')(member)}; }) }); } } $scope.sendSocialEventNotification = function () { $('#social-event-dialog').modal('hide'); ModalService.showModal({ templateUrl: "partials/socialEvents/send-notification-dialog.html", controller: "SocialEventNotificationsController", preClose: function (modal) { logger.debug('preClose event with modal', modal); modal.element.modal('hide'); }, inputs: { socialEvent: $scope.currentSocialEvent } }).then(function (modal) { logger.debug('modal event with modal', modal); modal.element.modal(); modal.close.then(function (result) { logger.debug('close event with result', result); }); }) }; function refreshSocialEvents() { if (URLService.hasRouteParameter('socialEventId')) { return SocialEventsService.getById($routeParams.socialEventId) .then(function (socialEvent) { if (!socialEvent) notify.error('Social event could not be found'); $scope.socialEvents = [socialEvent]; }); } else { var socialEvents = LoggedInMemberService.allowSocialDetailView() ? SocialEventsService.all() : SocialEventsService.all({ fields: { briefDescription: 1, eventDate: 1, thumbnail: 1 } }); socialEvents.then(function (socialEvents) { $scope.socialEvents = _.chain(socialEvents) .filter(function (socialEvent) { return socialEvent.eventDate >= $scope.todayValue }) .sortBy(function (socialEvent) { return socialEvent.eventDate; }) .value(); logger.debug('found', $scope.socialEvents.length, 'social events'); }); } } $q.when(refreshSocialEvents()) .then(refreshMembers) .then(refreshImages); function refreshImages() { ContentMetaDataService.getMetaData('imagesSocialEvents').then(function (contentMetaData) { $scope.interval = 5000; $scope.slides = contentMetaData.files; logger.debug('found', $scope.slides.length, 'slides'); }, function (response) { throw new Error(response); }); } }]); /* concatenated from client/src/app/js/urlServices.js */ angular.module('ekwgApp') .factory('URLService', ["$window", "$rootScope", "$timeout", "$location", "$routeParams", "$log", "PAGE_CONFIG", "ContentMetaDataService", function ($window, $rootScope, $timeout, $location, $routeParams, $log, PAGE_CONFIG, ContentMetaDataService) { var logger = $log.getInstance('URLService'); $log.logLevels['URLService'] = $log.LEVEL.OFF; function baseUrl(optionalUrl) { return _.first((optionalUrl || $location.absUrl()).split('/#')); } function relativeUrl(optionalUrl) { var relativeUrlValue = _.last((optionalUrl || $location.absUrl()).split("/#")); logger.debug("relativeUrlValue:", relativeUrlValue); return relativeUrlValue; } function relativeUrlFirstSegment(optionalUrl) { var relativeUrlValue = relativeUrl(optionalUrl); var index = relativeUrlValue.indexOf("/", 1); var relativeUrlFirstSegment = index === -1 ? relativeUrlValue : relativeUrlValue.substring(0, index); logger.debug("relativeUrl:", relativeUrlValue, "relativeUrlFirstSegment:", relativeUrlFirstSegment); return relativeUrlFirstSegment; } function resourceUrl(area, type, id) { return baseUrl() + '/#/' + area + '/' + type + 'Id/' + id; } function notificationHref(ctrl) { var href = (ctrl.name) ? resourceUrlForAWSFileName(ctrl.name) : resourceUrl(ctrl.area, ctrl.type, ctrl.id); logger.debug("href:", href); return href; } function resourceUrlForAWSFileName(fileName) { return baseUrl() + ContentMetaDataService.baseUrl(fileName); } function hasRouteParameter(parameter) { var hasRouteParameter = !!($routeParams[parameter]); logger.debug('hasRouteParameter', parameter, hasRouteParameter); return hasRouteParameter; } function isArea(areas) { logger.debug('isArea:areas', areas, '$routeParams', $routeParams); return _.some(_.isArray(areas) ? areas : [areas], function (area) { var matched = area === $routeParams.area; logger.debug('isArea', area, 'matched =', matched); return matched; }); } let pageUrl = function (page) { var pageOrEmpty = (page ? page : ""); return s.startsWith(pageOrEmpty, "/") ? pageOrEmpty : "/" + pageOrEmpty; }; function navigateTo(page, area) { $timeout(function () { var url = pageUrl(page) + (area ? "/" + area : ""); logger.info("navigating to page:", page, "area:", area, "->", url); $location.path(url); logger.info("$location.path is now", $location.path()) }, 1); } function navigateBackToLastMainPage() { var lastPage = _.chain($rootScope.pageHistory.reverse()) .find(function (page) { return _.contains(_.values(PAGE_CONFIG.mainPages), relativeUrlFirstSegment(page)); }) .value(); logger.info("navigateBackToLastMainPage:$rootScope.pageHistory", $rootScope.pageHistory, "lastPage->", lastPage); navigateTo(lastPage || "/") } function noArea() { return !$routeParams.area; } function setRoot() { return navigateTo(); } function area() { return $routeParams.area; } return { setRoot: setRoot, navigateBackToLastMainPage: navigateBackToLastMainPage, navigateTo: navigateTo, hasRouteParameter: hasRouteParameter, noArea: noArea, isArea: isArea, baseUrl: baseUrl, area: area, resourceUrlForAWSFileName: resourceUrlForAWSFileName, notificationHref: notificationHref, resourceUrl: resourceUrl, relativeUrlFirstSegment: relativeUrlFirstSegment, relativeUrl: relativeUrl } }]); /* concatenated from client/src/app/js/walkNotifications.js */ angular.module('ekwgApp') .controller('WalkNotificationsController', ["$log", "$scope", "WalkNotificationService", "RamblersWalksAndEventsService", function ($log, $scope, WalkNotificationService, RamblersWalksAndEventsService) { $scope.dataAuditDelta = WalkNotificationService.dataAuditDelta($scope.walk, $scope.status); $scope.validateWalk = RamblersWalksAndEventsService.validateWalk($scope.walk); RamblersWalksAndEventsService.walkBaseUrl().then(function (walkBaseUrl) { $scope.ramblersWalkBaseUrl = walkBaseUrl; }); }]) .factory('WalkNotificationService', ["$sce", "$log", "$timeout", "$filter", "$location", "$rootScope", "$q", "$compile", "$templateRequest", "$routeParams", "$cookieStore", "URLService", "MemberService", "MailchimpConfig", "MailchimpSegmentService", "WalksReferenceService", "MemberAuditService", "RamblersWalksAndEventsService", "MailchimpCampaignService", "LoggedInMemberService", "DateUtils", function ($sce, $log, $timeout, $filter, $location, $rootScope, $q, $compile, $templateRequest, $routeParams, $cookieStore, URLService, MemberService, MailchimpConfig, MailchimpSegmentService, WalksReferenceService, MemberAuditService, RamblersWalksAndEventsService, MailchimpCampaignService, LoggedInMemberService, DateUtils) { var logger = $log.getInstance('WalkNotificationService'); var noLogger = $log.getInstance('WalkNotificationServiceNoLog'); $log.logLevels['WalkNotificationService'] = $log.LEVEL.OFF; $log.logLevels['WalkNotificationServiceNoLog'] = $log.LEVEL.OFF; var basePartialsUrl = 'partials/walks/notifications'; var auditedFields = ['grade', 'walkDate', 'walkType', 'startTime', 'briefDescriptionAndStartPoint', 'longerDescription', 'distance', 'nearestTown', 'gridReference', 'meetupEventUrl', 'meetupEventTitle', 'osMapsRoute', 'osMapsTitle', 'postcode', 'walkLeaderMemberId', 'contactPhone', 'contactEmail', 'contactId', 'displayName', 'ramblersWalkId']; function currentDataValues(walk) { return _.compactObject(_.pick(walk, auditedFields)); } function previousDataValues(walk) { var event = latestWalkEvent(walk); return event && event.data || {}; } function latestWalkEvent(walk) { return (walk.events && _.last(walk.events)) || {}; } function eventsLatestFirst(walk) { var events = walk.events && _(walk.events).clone().reverse() || []; noLogger.info('eventsLatestFirst:', events); return events; } function latestEventWithStatusChange(walk) { return _(eventsLatestFirst(walk)).find(function (event) { return (WalksReferenceService.toEventType(event.eventType) || {}).statusChange; }) || {}; } function dataAuditDelta(walk, status) { if (!walk) return {}; var currentData = currentDataValues(walk); var previousData = previousDataValues(walk); var changedItems = calculateChangedItems(); var eventExists = latestEventWithStatusChangeIs(walk, status); var dataChanged = changedItems.length > 0; var dataAuditDelta = { currentData: currentData, previousData: previousData, changedItems: changedItems, eventExists: eventExists, dataChanged: dataChanged, notificationRequired: dataChanged || !eventExists, eventType: dataChanged && eventExists ? WalksReferenceService.eventTypes.walkDetailsUpdated.eventType : status }; dataAuditDelta.dataChanged && noLogger.info('dataAuditDelta', dataAuditDelta); return dataAuditDelta; function calculateChangedItems() { return _.compact(_.map(auditedFields, function (key) { var currentValue = currentData[key]; var previousValue = previousData[key]; noLogger.info('auditing', key, 'now:', currentValue, 'previous:', previousValue); if (previousValue !== currentValue) return { fieldName: key, previousValue: previousValue, currentValue: currentValue } })); } } function latestEventWithStatusChangeIs(walk, eventType) { if (!walk) return false; return latestEventWithStatusChange(walk).eventType === toEventTypeValue(eventType); } function toEventTypeValue(eventType) { return _.has(eventType, 'eventType') ? eventType.eventType : eventType; } function latestEventForEventType(walk, eventType) { if (walk) { var eventTypeString = toEventTypeValue(eventType); return eventsLatestFirst(walk).find(function (event) { return event.eventType === eventTypeString; }); } } function populateWalkApprovedEventsIfRequired(walks) { return _(walks).map(function (walk) { if (_.isArray(walk.events)) { return walk } else { var event = createEventIfRequired(walk, WalksReferenceService.eventTypes.approved.eventType, 'Marking past walk as approved'); writeEventIfRequired(walk, event); walk.$saveOrUpdate(); return walk; } }) } function createEventIfRequired(walk, status, reason) { var dataAuditDeltaInfo = dataAuditDelta(walk, status); logger.debug('createEventIfRequired:', dataAuditDeltaInfo); if (dataAuditDeltaInfo.notificationRequired) { var event = { "date": DateUtils.nowAsValue(), "memberId": LoggedInMemberService.loggedInMember().memberId, "data": dataAuditDeltaInfo.currentData, "eventType": dataAuditDeltaInfo.eventType }; if (reason) event.reason = reason; if (dataAuditDeltaInfo.dataChanged) event.description = 'Changed: ' + $filter('toAuditDeltaChangedItems')(dataAuditDeltaInfo.changedItems); logger.debug('createEventIfRequired: event created:', event); return event; } else { logger.debug('createEventIfRequired: event creation not necessary'); } } function writeEventIfRequired(walk, event) { if (event) { logger.debug('writing event', event); if (!_.isArray(walk.events)) walk.events = []; walk.events.push(event); } else { logger.debug('no event to write'); } } function createEventAndSendNotifications(members, walk, status, notify, sendNotification, reason) { notify.setBusy(); var event = createEventIfRequired(walk, status, reason); var notificationScope = $rootScope.$new(); notificationScope.walk = walk; notificationScope.members = members; notificationScope.event = event; notificationScope.status = status; var eventType = event && WalksReferenceService.toEventType(event.eventType); if (event && sendNotification) { return sendNotificationsToAllRoles() .then(function () { return writeEventIfRequired(walk, event); }) .then(function () { return true; }) .catch(function (error) { logger.debug('failed with error', error); return notify.error({title: error.message, message: error.error}) }); } else { logger.debug('Not sending notification'); return $q.when(writeEventIfRequired(walk, event)) .then(function () { return false; }); } function renderTemplateContent(templateData) { var task = $q.defer(); var templateFunction = $compile(templateData); var templateElement = templateFunction(notificationScope); $timeout(function () { notificationScope.$digest(); task.resolve(templateElement.html()); }); return task.promise; } function sendNotificationsToAllRoles() { return LoggedInMemberService.getMemberForMemberId(walk.walkLeaderMemberId) .then(function (member) { logger.debug('sendNotification:', 'memberId', walk.walkLeaderMemberId, 'member', member); var walkLeaderName = $filter('fullNameWithAlias')(member); var walkDate = $filter('displayDate')(walk.walkDate); return $q.when(notify.progress('Preparing to send email notifications')) .then(sendLeaderNotifications, notify.error, notify.progress) .then(sendCoordinatorNotifications, notify.error, notify.progress); function sendLeaderNotifications() { if (eventType.notifyLeader) return sendNotificationsTo({ templateUrl: templateForEvent('leader', eventType.eventType), memberIds: [walk.walkLeaderMemberId], segmentType: 'walkLeader', segmentName: MailchimpSegmentService.formatSegmentName('Walk leader notifications for ' + walkLeaderName), emailSubject: 'Your walk on ' + walkDate, destination: 'walk leader' }); logger.debug('not sending leader notification'); } function sendCoordinatorNotifications() { if (eventType.notifyCoordinator) { var memberIds = MemberService.allMemberIdsWithPrivilege('walkChangeNotifications', members); if (memberIds.length > 0) { return sendNotificationsTo({ templateUrl: templateForEvent('coordinator', eventType.eventType), memberIds: memberIds, segmentType: 'walkCoordinator', segmentName: MailchimpSegmentService.formatSegmentName('Walk co-ordinator notifications for ' + walkLeaderName), emailSubject: walkLeaderName + "'s walk on " + walkDate, destination: 'walk co-ordinators' }); } else { logger.debug('not sending coordinator notifications as none are configured with walkChangeNotifications'); } } else { logger.debug('not sending coordinator notifications as event type is', eventType.eventType); } } function templateForEvent(role, eventTypeString) { return basePartialsUrl + '/' + role + '/' + s.dasherize(eventTypeString) + '.html'; } function sendNotificationsTo(templateAndNotificationMembers) { if (templateAndNotificationMembers.memberIds.length === 0) throw new Error('No members have been configured as ' + templateAndNotificationMembers.destination + ' therefore notifications cannot be sent'); var memberFullNames = $filter('memberIdsToFullNames')(templateAndNotificationMembers.memberIds, members); logger.debug('sendNotificationsTo:', templateAndNotificationMembers); var campaignName = templateAndNotificationMembers.emailSubject + ' (' + eventType.description + ')'; var segmentName = templateAndNotificationMembers.segmentName; return $templateRequest($sce.getTrustedResourceUrl(templateAndNotificationMembers.templateUrl)) .then(renderTemplateContent, notify.error) .then(populateContentSections, notify.error) .then(sendNotification(templateAndNotificationMembers), notify.error); function populateContentSections(walkNotificationText) { logger.debug('populateContentSections -> walkNotificationText', walkNotificationText); return { sections: { notification_text: walkNotificationText } }; } function sendNotification(templateAndNotificationMembers) { return function (contentSections) { return createOrSaveMailchimpSegment() .then(saveSegmentDataToMember, notify.error, notify.progress) .then(sendEmailCampaign, notify.error, notify.progress) .then(notifyEmailSendComplete, notify.error, notify.success); function createOrSaveMailchimpSegment() { return MailchimpSegmentService.saveSegment('walks', {segmentId: MailchimpSegmentService.getMemberSegmentId(member, templateAndNotificationMembers.segmentType)}, templateAndNotificationMembers.memberIds, segmentName, members); } function saveSegmentDataToMember(segmentResponse) { MailchimpSegmentService.setMemberSegmentId(member, templateAndNotificationMembers.segmentType, segmentResponse.segment.id); return LoggedInMemberService.saveMember(member); } function sendEmailCampaign() { notify.progress('Sending ' + campaignName); return MailchimpConfig.getConfig() .then(function (config) { var campaignId = config.mailchimp.campaigns.walkNotification.campaignId; var segmentId = MailchimpSegmentService.getMemberSegmentId(member, templateAndNotificationMembers.segmentType); logger.debug('about to send campaign', campaignName, 'campaign Id', campaignId, 'segmentId', segmentId); return MailchimpCampaignService.replicateAndSendWithOptions({ campaignId: campaignId, campaignName: campaignName, contentSections: contentSections, segmentId: segmentId }); }) .then(function () { notify.progress('Sending of ' + campaignName + ' was successful', true); }); } function notifyEmailSendComplete() { notify.success('Sending of ' + campaignName + ' was successful. Check your inbox for details.'); return true; } } } } }); } } return { dataAuditDelta: dataAuditDelta, eventsLatestFirst: eventsLatestFirst, createEventIfRequired: createEventIfRequired, populateWalkApprovedEventsIfRequired: populateWalkApprovedEventsIfRequired, writeEventIfRequired: writeEventIfRequired, latestEventWithStatusChangeIs: latestEventWithStatusChangeIs, latestEventWithStatusChange: latestEventWithStatusChange, createEventAndSendNotifications: createEventAndSendNotifications } }]); /* concatenated from client/src/app/js/walkSlots.js.js */ angular.module('ekwgApp') .controller('WalkSlotsController', ["$rootScope", "$log", "$scope", "$filter", "$q", "WalksService", "WalksQueryService", "WalksReferenceService", "WalkNotificationService", "LoggedInMemberService", "DateUtils", "Notifier", function ($rootScope, $log, $scope, $filter, $q, WalksService, WalksQueryService, WalksReferenceService, WalkNotificationService, LoggedInMemberService, DateUtils, Notifier) { var logger = $log.getInstance('WalkSlotsController'); $log.logLevels['WalkSlotsController'] = $log.LEVEL.OFF; $scope.slotsAlert = {}; $scope.todayValue = DateUtils.momentNowNoTime().valueOf(); $scope.slot = { open: function ($event) { $event.preventDefault(); $event.stopPropagation(); $scope.slot.opened = true; }, validDate: function (date) { return DateUtils.isDate(date); }, until: DateUtils.momentNowNoTime().day(7 * 12).valueOf(), bulk: true }; var notify = Notifier($scope.slotsAlert); function createSlots(requiredSlots, confirmAction, prompt) { $scope.requiredWalkSlots = requiredSlots.map(function (date) { var walk = new WalksService({ walkDate: date }); walk.events = [WalkNotificationService.createEventIfRequired(walk, WalksReferenceService.eventTypes.awaitingLeader.eventType, 'Walk slot created')]; return walk; }); logger.debug('$scope.requiredWalkSlots', $scope.requiredWalkSlots); if ($scope.requiredWalkSlots.length > 0) { $scope.confirmAction = confirmAction; notify.warning(prompt) } else { notify.error({title: "Nothing to do!", message: "All slots are already created between today and " + $filter('displayDate')($scope.slot.until)}); delete $scope.confirmAction; } } $scope.addWalkSlots = function () { WalksService.query({walkDate: {$gte: $scope.todayValue}}, {fields: {events: 1, walkDate: 1}, sort: {walkDate: 1}}) .then(function (walks) { var sunday = DateUtils.momentNowNoTime().day(7); var untilDate = DateUtils.asMoment($scope.slot.until).startOf('day'); var weeks = untilDate.clone().diff(sunday, 'weeks'); var allGeneratedSlots = _.times(weeks, function (index) { return DateUtils.asValueNoTime(sunday.clone().add(index, 'week')); }).filter(function (date) { return DateUtils.asString(date, undefined, 'DD-MMM') !== '25-Dec'; }); var existingDates = _.pluck(WalksQueryService.activeWalks(walks), 'walkDate'); logger.debug('sunday', sunday, 'untilDate', untilDate, 'weeks', weeks); logger.debug('existingDatesAsDates', _(existingDates).map($filter('displayDateAndTime'))); logger.debug('allGeneratedSlotsAsDates', _(allGeneratedSlots).map($filter('displayDateAndTime'))); var requiredSlots = _.difference(allGeneratedSlots, existingDates); var requiredDates = $filter('displayDates')(requiredSlots); createSlots(requiredSlots, {addSlots: true}, { title: "Add walk slots", message: " - You are about to add " + requiredSlots.length + " empty walk slots up to " + $filter('displayDate')($scope.slot.until) + '. Slots are: ' + requiredDates }); }); }; $scope.addWalkSlot = function () { createSlots([DateUtils.asValueNoTime($scope.slot.single)], {addSlot: true}, { title: "Add walk slots", message: " - You are about to add 1 empty walk slot for " + $filter('displayDate')($scope.slot.single) }); }; $scope.selectBulk = function (bulk) { $scope.slot.bulk = bulk; delete $scope.confirmAction; notify.hide(); }; $scope.allow = { addSlot: function () { return !$scope.confirmAction && !$scope.slot.bulk && LoggedInMemberService.allowWalkAdminEdits(); }, addSlots: function () { return !$scope.confirmAction && $scope.slot.bulk && LoggedInMemberService.allowWalkAdminEdits(); }, close: function () { return !$scope.confirmAction; } }; $scope.cancelConfirmableAction = function () { delete $scope.confirmAction; notify.hide(); }; $scope.confirmAddWalkSlots = function () { notify.success({title: "Add walk slots - ", message: "now creating " + $scope.requiredWalkSlots.length + " empty walk slots up to " + $filter('displayDate')($scope.slot.until)}); $q.all($scope.requiredWalkSlots.map(function (slot) { return slot.$saveOrUpdate(); })).then(function () { notify.success({title: "Done!", message: "Choose Close to see your newly created slots"}); delete $scope.confirmAction; }); }; $scope.$on('addWalkSlotsDialogOpen', function () { $('#add-slots-dialog').modal(); delete $scope.confirmAction; notify.hide(); }); $scope.closeWalkSlotsDialog = function () { $('#add-slots-dialog').modal('hide'); $rootScope.$broadcast('walkSlotsCreated'); }; }] ); /* concatenated from client/src/app/js/walks.js */ angular.module('ekwgApp') .factory('WalksService', ["$mongolabResourceHttp", function ($mongolabResourceHttp) { return $mongolabResourceHttp('walks') }]) .factory('WalksQueryService', ["WalkNotificationService", "WalksReferenceService", function (WalkNotificationService, WalksReferenceService) { function activeWalks(walks) { return _.filter(walks, function (walk) { return !WalkNotificationService.latestEventWithStatusChangeIs(walk, WalksReferenceService.eventTypes.deleted) }) } return { activeWalks: activeWalks } }]) .factory('WalksReferenceService', function () { var eventTypes = { awaitingLeader: { statusChange: true, eventType: 'awaitingLeader', description: 'Awaiting walk leader' }, awaitingWalkDetails: { mustHaveLeader: true, statusChange: true, eventType: 'awaitingWalkDetails', description: 'Awaiting walk details from leader', notifyLeader: true, notifyCoordinator: true }, walkDetailsRequested: { mustHaveLeader: true, eventType: 'walkDetailsRequested', description: 'Walk details requested from leader', notifyLeader: true, notifyCoordinator: true }, walkDetailsUpdated: { eventType: 'walkDetailsUpdated', description: 'Walk details updated', notifyLeader: true, notifyCoordinator: true }, walkDetailsCopied: { eventType: 'walkDetailsCopied', description: 'Walk details copied' }, awaitingApproval: { mustHaveLeader: true, mustPassValidation: true, statusChange: true, eventType: 'awaitingApproval', readyToBe: 'approved', description: 'Awaiting confirmation of walk details', notifyLeader: true, notifyCoordinator: true }, approved: { mustHaveLeader: true, mustPassValidation: true, showDetails: true, statusChange: true, eventType: 'approved', readyToBe: 'published', description: 'Approved', notifyLeader: true, notifyCoordinator: true }, deleted: { statusChange: true, eventType: 'deleted', description: 'Deleted', notifyLeader: true, notifyCoordinator: true } }; return { toEventType: function (eventTypeString) { if (eventTypeString) { if (_.includes(eventTypeString, ' ')) eventTypeString = s.camelcase(eventTypeString.toLowerCase()); var eventType = eventTypes[eventTypeString]; if (!eventType) throw new Error("Event Type '" + eventTypeString + "' does not exist. Must be one of: " + _.keys(eventTypes).join(', ')); return eventType; } }, walkEditModes: { add: {caption: 'add', title: 'Add new'}, edit: {caption: 'edit', title: 'Edit existing', editEnabled: true}, more: {caption: 'more', title: 'View'}, lead: {caption: 'lead', title: 'Lead this', initialiseWalkLeader: true} }, eventTypes: eventTypes, walkStatuses: _(eventTypes).filter(function (eventType) { return eventType.statusChange; }) } }) .controller('WalksController', ["$sce", "$log", "$routeParams", "$interval", "$rootScope", "$location", "$scope", "$filter", "$q", "RamblersUploadAudit", "WalksService", "WalksQueryService", "URLService", "ClipboardService", "WalksReferenceService", "WalkNotificationService", "LoggedInMemberService", "MemberService", "DateUtils", "BatchGeoExportService", "RamblersWalksAndEventsService", "Notifier", "CommitteeReferenceData", "GoogleMapsConfig", "MeetupService", function ($sce, $log, $routeParams, $interval, $rootScope, $location, $scope, $filter, $q, RamblersUploadAudit, WalksService, WalksQueryService, URLService, ClipboardService, WalksReferenceService, WalkNotificationService, LoggedInMemberService, MemberService, DateUtils, BatchGeoExportService, RamblersWalksAndEventsService, Notifier, CommitteeReferenceData, GoogleMapsConfig, MeetupService) { var logger = $log.getInstance('WalksController'); var noLogger = $log.getInstance('WalksControllerNoLogger'); $log.logLevels['WalksControllerNoLogger'] = $log.LEVEL.OFF; $log.logLevels['WalksController'] = $log.LEVEL.OFF; $scope.contactUs = { ready: function () { return CommitteeReferenceData.ready; } }; $scope.$watch('filterParameters.quickSearch', function (quickSearch, oldQuery) { refreshFilteredWalks(); }); $scope.finalStatusError = function () { return _.findWhere($scope.ramblersUploadAudit, {status: "error"}); }; $scope.fileNameChanged = function () { logger.debug('filename changed to', $scope.userEdits.fileName); $scope.refreshRamblersUploadAudit(); }; $scope.refreshRamblersUploadAudit = function (stop) { logger.debug('refreshing audit trail records related to', $scope.userEdits.fileName); return RamblersUploadAudit.query({fileName: $scope.userEdits.fileName}, {sort: {auditTime: -1}}) .then(function (auditItems) { logger.debug('Filtering', auditItems.length, 'audit trail records related to', $scope.userEdits.fileName); $scope.ramblersUploadAudit = _.chain(auditItems) .filter(function (auditItem) { return $scope.userEdits.showDetail || auditItem.type !== "detail"; }) .map(function (auditItem) { if (auditItem.status === "complete") { logger.debug('Upload complete'); notifyWalkExport.success("Ramblers upload completed"); $interval.cancel(stop); $scope.userEdits.saveInProgress = false; } return auditItem; }) .value(); }); }; $scope.ramblersUploadAudit = []; $scope.walksForExport = []; $scope.walkEditModes = WalksReferenceService.walkEditModes; $scope.walkStatuses = WalksReferenceService.walkStatuses; $scope.walkAlert = {}; $scope.walkExport = {}; var notify = Notifier($scope); var notifyWalkExport = Notifier($scope.walkExport); var notifyWalkEdit = Notifier($scope.walkAlert); var SHOW_START_POINT = "show-start-point"; var SHOW_DRIVING_DIRECTIONS = "show-driving-directions"; notify.setBusy(); $scope.copyFrom = {walkTemplates: [], walkTemplate: {}}; $scope.userEdits = { copyToClipboard: ClipboardService.copyToClipboard, meetupEvent: {}, copySource: 'copy-selected-walk-leader', copySourceFromWalkLeaderMemberId: undefined, expandedWalks: [], mapDisplay: SHOW_START_POINT, longerDescriptionPreview: true, walkExportActive: function (activeTab) { return activeTab === $scope.walkExportActive; }, walkExportTab0Active: true, walkExportTab1Active: false, walkExportTabActive: 0, status: undefined, sendNotifications: true, saveInProgress: false, fileNames: [], walkLink: function (walk) { return walk && walk.$id() ? URLService.notificationHref({ type: "walk", area: "walks", id: walk.$id() }) : undefined } }; $scope.walks = []; $scope.busy = false; $scope.walksProgrammeOpen = URLService.isArea('programme', 'walkId') || URLService.noArea(); $scope.walksInformationOpen = URLService.isArea('information'); $scope.walksMapViewOpen = URLService.isArea('mapview'); $scope.todayValue = DateUtils.momentNowNoTime().valueOf(); $scope.userEdits.walkDateCalendar = { open: function ($event) { $event.preventDefault(); $event.stopPropagation(); $scope.userEdits.walkDateCalendar.opened = true; } }; $scope.addWalk = function () { showWalkDialog(new WalksService({ status: WalksReferenceService.eventTypes.awaitingLeader.eventType, walkType: $scope.type[0], walkDate: $scope.todayValue }), WalksReferenceService.walkEditModes.add); }; $scope.addWalkSlotsDialog = function () { $rootScope.$broadcast('addWalkSlotsDialogOpen'); }; $scope.unlinkRamblersDataFromCurrentWalk = function () { delete $scope.currentWalk.ramblersWalkId; notify.progress('Previous Ramblers walk has now been unlinked.') }; $scope.canUnlinkRamblers = function () { return LoggedInMemberService.allowWalkAdminEdits() && $scope.ramblersWalkExists(); }; $scope.notUploadedToRamblersYet = function () { return !$scope.ramblersWalkExists(); }; $scope.insufficientDataToUploadToRamblers = function () { return LoggedInMemberService.allowWalkAdminEdits() && $scope.currentWalk && !($scope.currentWalk.gridReference || $scope.currentWalk.postcode); }; $scope.canExportToRamblers = function () { return LoggedInMemberService.allowWalkAdminEdits() && $scope.validateWalk().selected; }; $scope.validateWalk = function () { return RamblersWalksAndEventsService.validateWalk($scope.currentWalk, $scope.members); }; $scope.walkValidations = function () { var walkValidations = $scope.validateWalk().walkValidations; return 'This walk cannot be included in the Ramblers Walks and Events Manager export due to the following ' + walkValidations.length + ' problem(s): ' + walkValidations.join(", ") + '.'; }; $scope.grades = ['Easy access', 'Easy', 'Leisurely', 'Moderate', 'Strenuous', 'Technical']; $scope.walkTypes = ['Circular', 'Linear']; $scope.meetupEventUrlChange = function (walk) { walk.meetupEventTitle = $scope.userEdits.meetupEvent.title; walk.meetupEventUrl = $scope.userEdits.meetupEvent.url; }; $scope.meetupSelectSync = function (walk) { $scope.userEdits.meetupEvent = _.findWhere($scope.meetupEvents, {url: walk.meetupEventUrl}); }; $scope.ramblersWalkExists = function () { return $scope.validateWalk().publishedOnRamblers }; function loggedInMemberIsLeadingWalk(walk) { return walk && walk.walkLeaderMemberId === LoggedInMemberService.loggedInMember().memberId } $scope.loggedIn = function () { return LoggedInMemberService.memberLoggedIn(); }; $scope.toWalkEditMode = function (walk) { if (LoggedInMemberService.memberLoggedIn()) { if (loggedInMemberIsLeadingWalk(walk) || LoggedInMemberService.allowWalkAdminEdits()) { return WalksReferenceService.walkEditModes.edit; } else if (!walk.walkLeaderMemberId) { return WalksReferenceService.walkEditModes.lead; } } }; $scope.actionWalk = function (walk) { showWalkDialog(walk, $scope.toWalkEditMode(walk)); }; $scope.deleteWalkDetails = function () { $scope.confirmAction = {delete: true}; notifyWalkEdit.warning({ title: 'Confirm delete of walk details.', message: 'If you confirm this, the slot for ' + $filter('displayDate')($scope.currentWalk.walkDate) + ' will be deleted from the site.' }); }; $scope.cancelWalkDetails = function () { $scope.confirmAction = {cancel: true}; notifyWalkEdit.warning({ title: 'Cancel changes.', message: 'Click Confirm to lose any changes you\'ve just made for ' + $filter('displayDate')($scope.currentWalk.walkDate) + ', or Cancel to carry on editing.' }); }; $scope.confirmCancelWalkDetails = function () { hideWalkDialogAndRefreshWalks(); }; function isWalkReadyForStatusChangeTo(eventType) { notifyWalkEdit.hide(); logger.info('isWalkReadyForStatusChangeTo ->', eventType); var walkValidations = $scope.validateWalk().walkValidations; if (eventType.mustHaveLeader && !$scope.currentWalk.walkLeaderMemberId) { notifyWalkEdit.warning( { title: 'Walk leader needed', message: ' - this walk cannot be changed to ' + eventType.description + ' yet.' }); revertToPriorWalkStatus(); return false; } else if (eventType.mustPassValidation && walkValidations.length > 0) { notifyWalkEdit.warning( { title: 'This walk is not ready to be ' + eventType.readyToBe + ' yet due to the following ' + walkValidations.length + ' problem(s): ', message: walkValidations.join(", ") + '. You can still save this walk, then come back later on to complete the rest of the details.' }); revertToPriorWalkStatus(); return false; } else { return true; } } function initiateEvent() { $scope.userEdits.saveInProgress = true; var walk = DateUtils.convertDateFieldInObject($scope.currentWalk, 'walkDate'); return WalkNotificationService.createEventAndSendNotifications($scope.members, walk, $scope.userEdits.status, notifyWalkEdit, $scope.userEdits.sendNotifications && walk.walkLeaderMemberId); } $scope.confirmDeleteWalkDetails = function () { $scope.userEdits.status = WalksReferenceService.eventTypes.deleted.eventType; return initiateEvent() .then(function () { return $scope.currentWalk.$saveOrUpdate(hideWalkDialogAndRefreshWalks, hideWalkDialogAndRefreshWalks); }) .catch(function () { $scope.userEdits.saveInProgress = false; }); }; $scope.saveWalkDetails = function () { return initiateEvent() .then(function (notificationSent) { return $scope.currentWalk.$saveOrUpdate(afterSaveWith(notificationSent), afterSaveWith(notificationSent)); }) .catch(function () { $scope.userEdits.saveInProgress = false; }); }; $scope.requestApproval = function () { logger.info('requestApproval called with current status:', $scope.userEdits.status); if (isWalkReadyForStatusChangeTo(WalksReferenceService.eventTypes.awaitingApproval)) { $scope.confirmAction = {requestApproval: true}; notifyWalkEdit.warning({ title: 'Confirm walk details complete.', message: 'If you confirm this, your walk details will be emailed to ' + walksCoordinatorName() + ' and they will publish these to the site.' }); } }; $scope.contactOther = function () { notifyWalkEdit.warning({ title: 'Confirm walk details complete.', message: 'If you confirm this, your walk details will be emailed to ' + walksCoordinatorName() + ' and they will publish these to the site.' }); }; $scope.walkStatusChange = function (status) { $scope.userEdits.priorStatus = status; notifyWalkEdit.hide(); logger.info('walkStatusChange - was:', status, 'now:', $scope.userEdits.status); if (isWalkReadyForStatusChangeTo(WalksReferenceService.toEventType($scope.userEdits.status))) switch ($scope.userEdits.status) { case WalksReferenceService.eventTypes.awaitingLeader.eventType: { var walkDate = $scope.currentWalk.walkDate; $scope.userEdits.status = WalksReferenceService.eventTypes.awaitingLeader.eventType; $scope.currentWalk = new WalksService(_.pick($scope.currentWalk, ['_id', 'events', 'walkDate'])); return notifyWalkEdit.success({ title: 'Walk details reset for ' + $filter('displayDate')(walkDate) + '.', message: 'Status is now ' + WalksReferenceService.eventTypes.awaitingLeader.description }); } case WalksReferenceService.eventTypes.approved.eventType: { return $scope.approveWalkDetails(); } } }; $scope.approveWalkDetails = function () { var walkValidations = $scope.validateWalk().walkValidations; if (walkValidations.length > 0) { notifyWalkEdit.warning({ title: 'This walk still has the following ' + walkValidations.length + ' field(s) that need attention: ', message: walkValidations.join(", ") + '. You\'ll have to get the rest of these details completed before you mark the walk as approved.' }); revertToPriorWalkStatus(); } else { notifyWalkEdit.success({ title: 'Ready to publish walk details!', message: 'All fields appear to be filled in okay, so next time you save this walk it will be published.' }); } }; $scope.confirmRequestApproval = function () { $scope.userEdits.status = WalksReferenceService.eventTypes.awaitingApproval.eventType; $scope.saveWalkDetails(); }; $scope.cancelConfirmableAction = function () { delete $scope.confirmAction; notify.hide(); notifyWalkEdit.hide(); }; function revertToPriorWalkStatus() { logger.info('revertToPriorWalkStatus:', $scope.userEdits.status, '->', $scope.userEdits.priorStatus); if ($scope.userEdits.priorStatus) $scope.userEdits.status = $scope.userEdits.priorStatus; } $scope.populateCurrentWalkFromTemplate = function () { var walkTemplate = _.clone($scope.copyFrom.walkTemplate); if (walkTemplate) { var templateDate = $filter('displayDate')(walkTemplate.walkDate); delete walkTemplate._id; delete walkTemplate.events; delete walkTemplate.ramblersWalkId; delete walkTemplate.walkDate; delete walkTemplate.displayName; delete walkTemplate.contactPhone; delete walkTemplate.contactEmail; angular.extend($scope.currentWalk, walkTemplate); var event = WalkNotificationService.createEventIfRequired($scope.currentWalk, WalksReferenceService.eventTypes.walkDetailsCopied.eventType, 'Copied from previous walk on ' + templateDate); WalkNotificationService.writeEventIfRequired($scope.currentWalk, event); notifyWalkEdit.success({ title: 'Walk details were copied from ' + templateDate + '.', message: 'Make any further changes here and save when you are done.' }); } }; $scope.filterParameters = { quickSearch: '', selectType: '1', ascending: "true" }; $scope.selectCopySelectedLeader = function () { $scope.userEdits.copySource = 'copy-selected-walk-leader'; $scope.populateWalkTemplates(); }; $scope.populateWalkTemplates = function (injectedMemberId) { var memberId = $scope.currentWalk.walkLeaderMemberId || injectedMemberId; var criteria; switch ($scope.userEdits.copySource) { case "copy-selected-walk-leader": { criteria = { walkLeaderMemberId: $scope.userEdits.copySourceFromWalkLeaderMemberId, briefDescriptionAndStartPoint: {$exists: true} }; break } case "copy-with-os-maps-route-selected": { criteria = {osMapsRoute: {$exists: true}}; break } default: { criteria = {walkLeaderMemberId: memberId}; } } logger.info('selecting walks', $scope.userEdits.copySource, criteria); WalksService.query(criteria, {sort: {walkDate: -1}}) .then(function (walks) { $scope.copyFrom.walkTemplates = walks; }); }; $scope.walkLeaderMemberIdChanged = function () { notifyWalkEdit.hide(); var walk = $scope.currentWalk; var memberId = walk.walkLeaderMemberId; if (!memberId) { $scope.userEdits.status = WalksReferenceService.eventTypes.awaitingLeader.eventType; delete walk.walkLeaderMemberId; delete walk.contactId; delete walk.displayName; delete walk.contactPhone; delete walk.contactEmail; } else { var selectedMember = _.find($scope.members, function (member) { return member.$id() === memberId; }); if (selectedMember) { $scope.userEdits.status = WalksReferenceService.eventTypes.awaitingWalkDetails.eventType; walk.contactId = selectedMember.contactId; walk.displayName = selectedMember.displayName; walk.contactPhone = selectedMember.mobileNumber; walk.contactEmail = selectedMember.email; $scope.populateWalkTemplates(memberId); } } }; $scope.myOrWalkLeader = function () { return loggedInMemberIsLeadingWalk($scope.currentWalk) ? 'my' : $scope.currentWalk && $scope.currentWalk.displayName + "'s"; }; $scope.meOrWalkLeader = function () { return loggedInMemberIsLeadingWalk($scope.currentWalk) ? 'me' : $scope.currentWalk && $scope.currentWalk.displayName; }; $scope.personToNotify = function () { return loggedInMemberIsLeadingWalk($scope.currentWalk) ? walksCoordinatorName() : $scope.currentWalk && $scope.currentWalk.displayName; }; function walksCoordinatorName() { return CommitteeReferenceData.contactUsField('walks', 'fullName'); } function convertWalkDateIfNotNumeric(walk) { var walkDate = DateUtils.asValueNoTime(walk.walkDate); if (walkDate !== walk.walkDate) { logger.info('Converting date from', walk.walkDate, '(' + $filter('displayDateAndTime')(walk.walkDate) + ') to', walkDate, '(' + $filter('displayDateAndTime')(walkDate) + ')'); walk.walkDate = walkDate; } else { logger.info('Walk date', walk.walkDate, 'is already in correct format'); } return walk; } function latestEventWithStatusChangeIs(eventType) { return WalkNotificationService.latestEventWithStatusChangeIs($scope.currentWalk, eventType); } $scope.dataHasChanged = function () { var dataAuditDelta = WalkNotificationService.dataAuditDelta($scope.currentWalk, $scope.userEdits.status); var notificationRequired = dataAuditDelta.notificationRequired; dataAuditDelta.notificationRequired && noLogger.info('dataAuditDelta - eventExists:', dataAuditDelta.eventExists, 'dataChanged:', dataAuditDelta.dataChanged, $filter('toAuditDeltaChangedItems')(dataAuditDelta.changedItems)); dataAuditDelta.dataChanged && noLogger.info('dataAuditDelta - previousData:', dataAuditDelta.previousData, 'currentData:', dataAuditDelta.currentData); return notificationRequired; }; function ownedAndAwaitingWalkDetails() { return loggedInMemberIsLeadingWalk($scope.currentWalk) && $scope.userEdits.status === WalksReferenceService.eventTypes.awaitingWalkDetails.eventType; } function editable() { return !$scope.confirmAction && (LoggedInMemberService.allowWalkAdminEdits() || loggedInMemberIsLeadingWalk($scope.currentWalk)); } function allowSave() { return editable() && $scope.dataHasChanged(); } $scope.allow = { close: function () { return !$scope.userEdits.saveInProgress && !$scope.confirmAction && !allowSave() }, save: allowSave, cancel: function () { return !$scope.userEdits.saveInProgress && editable() && $scope.dataHasChanged(); }, delete: function () { return !$scope.confirmAction && LoggedInMemberService.allowWalkAdminEdits() && $scope.walkEditMode && $scope.walkEditMode.editEnabled; }, notifyConfirmation: function () { return (allowSave() || $scope.confirmAction && $scope.confirmAction.delete) && $scope.currentWalk.walkLeaderMemberId; }, adminEdits: function () { return LoggedInMemberService.allowWalkAdminEdits(); }, edits: editable, historyView: function () { return loggedInMemberIsLeadingWalk($scope.currentWalk) || LoggedInMemberService.allowWalkAdminEdits(); }, detailView: function () { return LoggedInMemberService.memberLoggedIn(); }, approve: function () { return !$scope.confirmAction && LoggedInMemberService.allowWalkAdminEdits() && latestEventWithStatusChangeIs(WalksReferenceService.eventTypes.awaitingApproval); }, requestApproval: function () { return !$scope.confirmAction && ownedAndAwaitingWalkDetails(); } }; $scope.previewLongerDescription = function () { logger.debug('previewLongerDescription'); $scope.userEdits.longerDescriptionPreview = true; }; $scope.editLongerDescription = function () { logger.debug('editLongerDescription'); $scope.userEdits.longerDescriptionPreview = false; }; $scope.trustSrc = function (src) { return $sce.trustAsResourceUrl(src); }; $scope.showAllWalks = function () { $scope.expensesOpen = true; $location.path('/walks/programme') }; $scope.googleMaps = function (walk) { return $scope.userEdits.mapDisplay === SHOW_DRIVING_DIRECTIONS ? "https://www.google.com/maps/embed/v1/directions?origin=" + $scope.userEdits.fromPostcode + "&destination=" + walk.postcode + "&key=" + $scope.googleMapsConfig.apiKey : "https://www.google.com/maps/embed/v1/place?q=" + walk.postcode + "&zoom=" + $scope.googleMapsConfig.zoomLevel + "&key=" + $scope.googleMapsConfig.apiKey; }; $scope.autoSelectMapDisplay = function () { var switchToShowStartPoint = $scope.drivingDirectionsDisabled() && $scope.userEdits.mapDisplay === SHOW_DRIVING_DIRECTIONS; var switchToShowDrivingDirections = !$scope.drivingDirectionsDisabled() && $scope.userEdits.mapDisplay === SHOW_START_POINT; if (switchToShowStartPoint) { $scope.userEdits.mapDisplay = SHOW_START_POINT; } else if (switchToShowDrivingDirections) { $scope.userEdits.mapDisplay = SHOW_DRIVING_DIRECTIONS; } }; $scope.drivingDirectionsDisabled = function () { return $scope.userEdits.fromPostcode.length < 3; }; $scope.eventTypeFor = function (walk) { var latestEventWithStatusChange = WalkNotificationService.latestEventWithStatusChange(walk); var eventType = WalksReferenceService.toEventType(latestEventWithStatusChange.eventType) || walk.status || WalksReferenceService.eventTypes.awaitingWalkDetails.eventType; noLogger.info('latestEventWithStatusChange', latestEventWithStatusChange, 'eventType', eventType, 'walk.events', walk.events); return eventType; }; $scope.viewWalkField = function (walk, field) { var eventType = $scope.eventTypeFor(walk); if (eventType.showDetails) { return walk[field] || ''; } else if (field === 'briefDescriptionAndStartPoint') { return eventType.description; } else { return ''; } }; function showWalkDialog(walk, walkEditMode) { delete $scope.confirmAction; $scope.userEdits.sendNotifications = true; $scope.walkEditMode = walkEditMode; $scope.currentWalk = walk; if (walkEditMode.initialiseWalkLeader) { $scope.userEdits.status = WalksReferenceService.eventTypes.awaitingWalkDetails.eventType; walk.walkLeaderMemberId = LoggedInMemberService.loggedInMember().memberId; $scope.walkLeaderMemberIdChanged(); notifyWalkEdit.success({ title: 'Thanks for offering to lead this walk ' + LoggedInMemberService.loggedInMember().firstName + '!', message: 'Please complete as many details you can, then save to allocate this slot on the walks programme. ' + 'It will be published to the public once it\'s approved. If you want to release this slot again, just click cancel.' }); } else { var eventTypeIfExists = WalkNotificationService.latestEventWithStatusChange($scope.currentWalk).eventType; if (eventTypeIfExists) { $scope.userEdits.status = eventTypeIfExists } $scope.userEdits.copySourceFromWalkLeaderMemberId = walk.walkLeaderMemberId || LoggedInMemberService.loggedInMember().memberId; $scope.populateWalkTemplates(); $scope.meetupSelectSync($scope.currentWalk); notifyWalkEdit.hide(); } $('#walk-dialog').modal(); } function walksCriteriaObject() { switch ($scope.filterParameters.selectType) { case '1': return {walkDate: {$gte: $scope.todayValue}}; case '2': return {walkDate: {$lt: $scope.todayValue}}; case '3': return {}; case '4': return {displayName: {$exists: false}}; case '5': return {briefDescriptionAndStartPoint: {$exists: false}}; } } function walksSortObject() { switch ($scope.filterParameters.ascending) { case 'true': return {sort: {walkDate: 1}}; case 'false': return {sort: {walkDate: -1}}; } } function query() { if (URLService.hasRouteParameter('walkId')) { return WalksService.getById($routeParams.walkId) .then(function (walk) { if (!walk) notify.error('Walk could not be found. Try opening again from the link in the notification email, or choose the Show All Walks button'); return [walk]; }); } else { return WalksService.query(walksCriteriaObject(), walksSortObject()); } } function refreshFilteredWalks() { notify.setBusy(); $scope.filteredWalks = $filter('filter')($scope.walks, $scope.filterParameters.quickSearch); var walksCount = ($scope.filteredWalks && $scope.filteredWalks.length) || 0; notify.progress('Showing ' + walksCount + ' walk(s)'); if ($scope.filteredWalks.length > 0) { $scope.userEdits.expandedWalks = [$scope.filteredWalks[0].$id()]; } notify.clearBusy(); } $scope.showTableHeader = function (walk) { return $scope.filteredWalks.indexOf(walk) === 0 || $scope.isExpandedFor($scope.filteredWalks[$scope.filteredWalks.indexOf(walk) - 1]); }; $scope.nextWalk = function (walk) { return walk && walk.$id() === $scope.nextWalkId; }; $scope.durationInFutureFor = function (walk) { return walk && walk.walkDate === $scope.todayValue ? 'today' : (DateUtils.asMoment(walk.walkDate).fromNow()); }; $scope.toggleViewFor = function (walk) { function arrayRemove(arr, value) { return arr.filter(function (ele) { return ele !== value; }); } var walkId = walk.$id(); if (_.contains($scope.userEdits.expandedWalks, walkId)) { $scope.userEdits.expandedWalks = arrayRemove($scope.userEdits.expandedWalks, walkId); logger.debug('toggleViewFor:', walkId, '-> collapsing'); } else { $scope.userEdits.expandedWalks.push(walkId); logger.debug('toggleViewFor:', walkId, '-> expanding'); } logger.debug('toggleViewFor:', walkId, '-> expandedWalks contains', $scope.userEdits.expandedWalks) }; $scope.isExpandedFor = function (walk) { return _.contains($scope.userEdits.expandedWalks, walk.$id()); }; $scope.tableRowOdd = function (walk) { return $scope.filteredWalks.indexOf(walk) % 2 === 0; }; function getNextWalkId(walks) { var nextWalk = _.chain(walks).sortBy('walkDate').find(function (walk) { return walk.walkDate >= $scope.todayValue; }).value(); return nextWalk && nextWalk.$id(); } $scope.refreshWalks = function (notificationSent) { notify.setBusy(); notify.progress('Refreshing walks...'); return query() .then(function (walks) { $scope.nextWalkId = URLService.hasRouteParameter('walkId') ? undefined : getNextWalkId(walks); $scope.walks = URLService.hasRouteParameter('walkId') ? walks : WalksQueryService.activeWalks(walks); refreshFilteredWalks(); notify.clearBusy(); if (!notificationSent) { notifyWalkEdit.hide(); } $scope.userEdits.saveInProgress = false; }); }; $scope.hideWalkDialog = function () { $('#walk-dialog').modal('hide'); delete $scope.confirmAction; }; function hideWalkDialogAndRefreshWalks() { logger.info('hideWalkDialogAndRefreshWalks'); $scope.hideWalkDialog(); $scope.refreshWalks(); } function afterSaveWith(notificationSent) { return function () { if (!notificationSent) $('#walk-dialog').modal('hide'); notifyWalkEdit.clearBusy(); delete $scope.confirmAction; $scope.refreshWalks(notificationSent); $scope.userEdits.saveInProgress = false; } } function refreshRamblersConfig() { RamblersWalksAndEventsService.walkBaseUrl().then(function (walkBaseUrl) { $scope.ramblersWalkBaseUrl = walkBaseUrl; }); } function refreshGoogleMapsConfig() { GoogleMapsConfig.getConfig().then(function (googleMapsConfig) { $scope.googleMapsConfig = googleMapsConfig; $scope.googleMapsConfig.zoomLevel = 12; }); } function refreshMeetupData() { MeetupService.config().then(function (meetupConfig) { $scope.meetupConfig = meetupConfig; }); MeetupService.eventsForStatus('past') .then(function (pastEvents) { MeetupService.eventsForStatus('upcoming') .then(function (futureEvents) { $scope.meetupEvents = _.sortBy(pastEvents.concat(futureEvents), 'date,').reverse(); }); }) } function refreshHomePostcode() { $scope.userEdits.fromPostcode = LoggedInMemberService.memberLoggedIn() ? LoggedInMemberService.loggedInMember().postcode : ""; logger.debug('set from postcode to', $scope.userEdits.fromPostcode); $scope.autoSelectMapDisplay(); } $scope.$on('memberLoginComplete', function () { refreshMembers(); refreshHomePostcode(); }); $scope.$on('walkSlotsCreated', function () { $scope.refreshWalks(); }); function refreshMembers() { if (LoggedInMemberService.memberLoggedIn()) MemberService.allLimitedFields(MemberService.filterFor.GROUP_MEMBERS) .then(function (members) { $scope.members = members; return members; }); } $scope.batchGeoDownloadFile = function () { return BatchGeoExportService.exportWalks($scope.walks, $scope.members); }; $scope.batchGeoDownloadFileName = function () { return BatchGeoExportService.exportWalksFileName(); }; $scope.batchGeoDownloadHeader = function () { return BatchGeoExportService.exportColumnHeadings(); }; $scope.exportableWalks = function () { return RamblersWalksAndEventsService.exportableWalks($scope.walksForExport); }; $scope.walksDownloadFile = function () { return RamblersWalksAndEventsService.exportWalks($scope.exportableWalks(), $scope.members); }; $scope.uploadToRamblers = function () { $scope.ramblersUploadAudit = []; $scope.userEdits.walkExportTab0Active = false; $scope.userEdits.walkExportTab1Active = true; $scope.userEdits.saveInProgress = true; RamblersWalksAndEventsService.uploadToRamblers($scope.walksForExport, $scope.members, notifyWalkExport).then(function (fileName) { $scope.userEdits.fileName = fileName; var stop = $interval(callAtInterval, 2000, false); if (!_.contains($scope.userEdits.fileNames, $scope.userEdits.fileName)) { $scope.userEdits.fileNames.push($scope.userEdits.fileName); logger.debug('added', $scope.userEdits.fileName, 'to filenames of', $scope.userEdits.fileNames.length, 'audit trail records'); } delete $scope.finalStatusError; function callAtInterval() { logger.debug("Refreshing audit trail for file", $scope.userEdits.fileName, 'count =', $scope.ramblersUploadAudit.length); $scope.refreshRamblersUploadAudit(stop); } }); }; $scope.walksDownloadFileName = function () { return RamblersWalksAndEventsService.exportWalksFileName(); }; $scope.walksDownloadHeader = function () { return RamblersWalksAndEventsService.exportColumnHeadings(); }; $scope.selectWalksForExport = function () { showWalkExportDialog(); }; $scope.changeWalkExportSelection = function (walk) { if (walk.walkValidations.length === 0) { walk.selected = !walk.selected; notifyWalkExport.hide(); } else { notifyWalkExport.error({ title: 'You can\'t export the walk for ' + $filter('displayDate')(walk.walk.walkDate), message: walk.walkValidations.join(', ') }); } }; $scope.cancelExportWalkDetails = function () { $('#walk-export-dialog').modal('hide'); }; function populateWalkExport(walksForExport) { $scope.walksForExport = walksForExport; notifyWalkExport.success('Found total of ' + $scope.walksForExport.length + ' walk(s), ' + $scope.walksDownloadFile().length + ' preselected for export'); notifyWalkExport.clearBusy(); } function showWalkExportDialog() { $scope.walksForExport = []; notifyWalkExport.warning('Determining which walks to export', true); RamblersUploadAudit.all({limit: 1000, sort: {auditTime: -1}}) .then(function (auditItems) { logger.debug('found total of', auditItems.length, 'audit trail records'); $scope.userEdits.fileNames = _.chain(auditItems).pluck('fileName').unique().value(); logger.debug('unique total of', $scope.userEdits.fileNames.length, 'audit trail records'); }); RamblersWalksAndEventsService.createWalksForExportPrompt($scope.walks, $scope.members) .then(populateWalkExport) .catch(function (error) { logger.debug('error->', error); notifyWalkExport.error({title: 'Problem with Ramblers export preparation', message: JSON.stringify(error)}); }); $('#walk-export-dialog').modal(); } refreshMembers(); $scope.refreshWalks(); refreshRamblersConfig(); refreshGoogleMapsConfig(); refreshMeetupData(); refreshHomePostcode(); }] ) ;
nbarrett/ekwg
dist/app/js/ekwg.js
JavaScript
mit
405,222
angular.module('MEANcraftApp', ['ngRoute', 'MEANcraftApp.login', 'MEANcraftApp.overview', 'btford.socket-io'/*,'socket-io', 'flow'*/]) .config(function ($httpProvider, $routeProvider) { $httpProvider.interceptors.push('TokenInterceptor'); $routeProvider .when('/login', { templateUrl: 'app/login/login', controller: 'loginCtrl', protect: false }) .when('/overview', { templateUrl: 'app/overview/overview', //controller: 'overviewCtrl', protect: true, resolve: { initialData: function (ServerSocket, FetchData, $q) { return $q(function (resolve, reject) { ServerSocket.emit('info'); ServerSocket.once('info', function (data) { console.log(data); FetchData = angular.extend(FetchData, data); resolve(); }); }); } } }) .otherwise({ redirectTo: '/overview' }); }) .run(function ($rootScope, $location, $window, $routeParams, UserAuth) { if (!UserAuth.isLogged) { $location.path('/login'); } $rootScope.$on('$routeChangeStart', function (event, nextRoute, prevRoute) { console.groupCollapsed('%cAPP.RUN -> ROUTE CHANGE START', 'background: #222; color: #bada55;'); console.log('%cTOKEN -> %c' + $window.sessionStorage.token, 'font-weight: bold', ''); console.log('%cLOGGIN STATUS -> %c' + UserAuth.isLogged, 'font-weight: bold', UserAuth.isLogged ? 'color: green;' : 'color: red;'); console.groupEnd('APP.RUN -> ROUTE CHANGE START'); if (nextRoute.protect && UserAuth.isLogged === false && !$window.sessionStorage.token) { $location.path('/login'); console.error('Route protected, user not logged in'); } else if (!nextRoute.protect && UserAuth.isLogged) { $location.path('/overview'); } }); });
frotunato/MEANcraft
client/app/app.js
JavaScript
mit
1,953
var GridLayout = require("ui/layouts/grid-layout").GridLayout; var ListView = require("ui/list-view").ListView; var StackLayout = require("ui/layouts/stack-layout").StackLayout; var Image = require("ui/image").Image; var Label = require("ui/label").Label; var ScrapbookList = (function (_super) { global.__extends(ScrapbookList, _super); Object.defineProperty(ScrapbookList.prototype, "items", { get: function() { return this._items; }, set: function(value) { this._items = value; this.bindData(); } }); function ScrapbookList() { _super.call(this); this._items; this.rows = "*"; this.columns = "*"; var listView = new ListView(); listView.className = "list-group"; listView.itemTemplate = function() { var stackLayout = new StackLayout(); stackLayout.orientation = "horizontal"; stackLayout.bind({ targetProperty: "className", sourceProperty: "$value", expression: "isActive ? 'list-group-item active' : 'list-group-item'" }); var image = new Image(); image.className = "thumb img-circle"; image.bind({ targetProperty: "src", sourceProperty: "image" }); stackLayout.addChild(image); var label = new Label(); label.className = "list-group-item-text"; label.style.width = "100%"; label.textWrap = true; label.bind({ targetProperty: "text", sourceProperty: "title", expression: "(title === null || title === undefined ? 'New' : title + '\\\'s') + ' Scrapbook Page'" }); stackLayout.addChild(label); return stackLayout; }; listView.on(ListView.itemTapEvent, function(args) { onItemTap(this, args.index); }.bind(listView)); this.addChild(listView); this.bindData = function () { listView.bind({ sourceProperty: "$value", targetProperty: "items", twoWay: "true" }, this._items); }; var onItemTap = function(args, index) { this.notify({ eventName: "itemTap", object: this, index: index }); }.bind(this); } return ScrapbookList; })(GridLayout); ScrapbookList.itemTapEvent = "itemTap"; exports.ScrapbookList = ScrapbookList;
mikebranstein/NativeScriptInAction
AppendixB/PetScrapbook/app/views/shared/scrapbook-list/scrapbook-list.js
JavaScript
mit
3,048
<?php /** * @package toolkit */ /** * The Datasource class provides functionality to mainly process any parameters * that the fields will use in filters find the relevant Entries and return these Entries * data as XML so that XSLT can be applied on it to create your website. In Symphony, * there are four Datasource types provided, Section, Author, Navigation and Dynamic * XML. Section is the mostly commonly used Datasource, which allows the filtering * and searching for Entries in a Section to be returned as XML. Navigation datasources * expose the Symphony Navigation structure of the Pages in the installation. Authors * expose the Symphony Authors that are registered as users of the backend. Finally, * the Dynamic XML datasource allows XML pages to be retrieved. This is especially * helpful for working with Restful XML API's. Datasources are saved through the * Symphony backend, which uses a Datasource template defined in * `TEMPLATE . /datasource.tpl`. */ class DataSource { /** * A constant that represents if this filter is an AND filter in which * an Entry must match all these filters. This filter is triggered when * the filter string contains a ` + `. * * @since Symphony 2.3.2 * @var integer */ const FILTER_AND = 1; /** * A constant that represents if this filter is an OR filter in which an * entry can match any or all of these filters * * @since Symphony 2.3.2 * @var integer */ const FILTER_OR = 2; /** * Holds all the environment variables which include parameters set by * other Datasources or Events. * @var array */ protected $_env = array(); /** * If true, this datasource only will be outputting parameters from the * Entries, and no actual content. * @var boolean */ protected $_param_output_only; /** * An array of datasource dependancies. These are datasources that must * run first for this datasource to be able to execute correctly * @var array */ protected $_dependencies = array(); /** * When there is no entries found by the Datasource, this parameter will * be set to true, which will inject the default Symphony 'No records found' * message into the datasource's result * @var boolean */ protected $_force_empty_result = false; /** * When there is a negating parameter, this parameter will * be set to true, which will inject the default Symphony 'Results Negated' * message into the datasource's result * @var boolean */ protected $_negate_result = false; /** * Constructor for the datasource sets the parent, if `$process_params` is set, * the `$env` variable will be run through `Datasource::processParameters`. * * @see toolkit.Datasource#processParameters() * @param array $env * The environment variables from the Frontend class which includes * any params set by Symphony or Events or by other Datasources * @param boolean $process_params * If set to true, `Datasource::processParameters` will be called. By default * this is true * @throws FrontendPageNotFoundException */ public function __construct(array $env = null, $process_params = true) { // Support old the __construct (for the moment anyway). // The old signature was array/array/boolean // The new signature is array/boolean $arguments = func_get_args(); if (count($arguments) == 3 && is_bool($arguments[1]) && is_bool($arguments[2])) { $env = $arguments[0]; $process_params = $arguments[1]; } if ($process_params) { $this->processParameters($env); } } /** * This function is required in order to edit it in the datasource editor page. * Do not overload this function if you are creating a custom datasource. It is only * used by the datasource editor. If this is set to false, which is default, the * Datasource's `about()` information will be displayed. * * @return boolean * True if the Datasource can be edited, false otherwise. Defaults to false */ public function allowEditorToParse() { return false; } /** * This function is required in order to identify what section this Datasource is for. It * is used in the datasource editor. It must remain intact. Do not overload this function in * custom events. Other datasources may return a string here defining their datasource * type when they do not query a section. * * @return mixed */ public function getSource() { return null; } /** * Accessor function to return this Datasource's dependencies * * @return array */ public function getDependencies() { return $this->_dependencies; } /** * Returns an associative array of information about a datasource. * * @return array */ public function about() { return array(); } /** * @deprecated This function has been renamed to `execute` as of * Symphony 2.3.1, please use `execute()` instead. This function will * be removed in Symphony 2.5 * @see execute() */ public function grab(array &$param_pool = null) { return $this->execute($param_pool); } /** * The meat of the Datasource, this function includes the datasource * type's file that will preform the logic to return the data for this datasource * It is passed the current parameters. * * @param array $param_pool * The current parameter pool that this Datasource can use when filtering * and finding Entries or data. * @return XMLElement * The XMLElement to add into the XML for a page. */ public function execute(array &$param_pool = null) { $result = new XMLElement($this->dsParamROOTELEMENT); try { $result = $this->execute($param_pool); } catch (FrontendPageNotFoundException $e) { // Work around. This ensures the 404 page is displayed and // is not picked up by the default catch() statement below FrontendPageNotFoundExceptionHandler::render($e); } catch (Exception $e) { $result->appendChild(new XMLElement('error', $e->getMessage())); return $result; } if ($this->_force_empty_result) { $result = $this->emptyXMLSet(); } if ($this->_negate_result) { $result = $this->negateXMLSet(); } return $result; } /** * By default, all Symphony filters are considering to be AND filters, that is * they are all used and Entries must match each filter to be included. It is * possible to use OR filtering in a field by using an + to separate the values. * eg. If the filter is test1 + test2, this will match any entries where this field * is test1 OR test2. This function is run on each filter (ie. each field) in a * datasource * * @param string $value * The filter string for a field. * @return integer * DataSource::FILTER_OR or DataSource::FILTER_AND */ public function __determineFilterType($value) { return (preg_match('/\s+\+\s+/', $value) ? DataSource::FILTER_AND : DataSource::FILTER_OR); } /** * If there is no results to return this function calls `Datasource::__noRecordsFound` * which appends an XMLElement to the current root element. * * @param XMLElement $xml * The root element XMLElement for this datasource. By default, this will * the handle of the datasource, as defined by `$this->dsParamROOTELEMENT` * @return XMLElement */ public function emptyXMLSet(XMLElement $xml = null) { if (is_null($xml)) { $xml = new XMLElement($this->dsParamROOTELEMENT); } $xml->appendChild($this->__noRecordsFound()); return $xml; } /** * If the datasource has been negated this function calls `Datasource::__negateResult` * which appends an XMLElement to the current root element. * * @param XMLElement $xml * The root element XMLElement for this datasource. By default, this will * the handle of the datasource, as defined by `$this->dsParamROOTELEMENT` * @return XMLElement */ public function negateXMLSet(XMLElement $xml = null) { if (is_null($xml)) { $xml = new XMLElement($this->dsParamROOTELEMENT); } $xml->appendChild($this->__negateResult()); return $xml; } /** * Returns an error XMLElement with 'No records found' text * * @return XMLElement */ public function __noRecordsFound() { return new XMLElement('error', __('No records found.')); } /** * Returns an error XMLElement with 'Result Negated' text * * @return XMLElement */ public function __negateResult() { $error = new XMLElement('error', __("Data source not executed, forbidden parameter was found."), array( 'forbidden-param' => $this->dsParamNEGATEPARAM )); return $error; } /** * This function will iterates over the filters and replace any parameters with their * actual values. All other Datasource variables such as sorting, ordering and * pagination variables are also set by this function * * @param array $env * The environment variables from the Frontend class which includes * any params set by Symphony or Events or by other Datasources * @throws FrontendPageNotFoundException */ public function processParameters(array $env = null) { if ($env) { $this->_env = $env; } if ((isset($this->_env) && is_array($this->_env)) && isset($this->dsParamFILTERS) && is_array($this->dsParamFILTERS) && !empty($this->dsParamFILTERS)) { foreach ($this->dsParamFILTERS as $key => $value) { $value = stripslashes($value); $new_value = $this->__processParametersInString($value, $this->_env); // If a filter gets evaluated to nothing, eg. ` + ` or ``, then remove // the filter. RE: #1759 if (strlen(trim($new_value)) == 0 || !preg_match('/\w+/', $new_value)) { unset($this->dsParamFILTERS[$key]); } else { $this->dsParamFILTERS[$key] = $new_value; } } } if (isset($this->dsParamORDER)) { $this->dsParamORDER = $this->__processParametersInString($this->dsParamORDER, $this->_env); } if (isset($this->dsParamSORT)) { $this->dsParamSORT = $this->__processParametersInString($this->dsParamSORT, $this->_env); } if (isset($this->dsParamSTARTPAGE)) { $this->dsParamSTARTPAGE = $this->__processParametersInString($this->dsParamSTARTPAGE, $this->_env); if ($this->dsParamSTARTPAGE == '') { $this->dsParamSTARTPAGE = '1'; } } if (isset($this->dsParamLIMIT)) { $this->dsParamLIMIT = $this->__processParametersInString($this->dsParamLIMIT, $this->_env); } if ( isset($this->dsParamREQUIREDPARAM) && strlen(trim($this->dsParamREQUIREDPARAM)) > 0 && $this->__processParametersInString(trim($this->dsParamREQUIREDPARAM), $this->_env, false) == '' ) { $this->_force_empty_result = true; // don't output any XML $this->dsParamPARAMOUTPUT = null; // don't output any parameters $this->dsParamINCLUDEDELEMENTS = null; // don't query any fields in this section return; } if ( isset($this->dsParamNEGATEPARAM) && strlen(trim($this->dsParamNEGATEPARAM)) > 0 && $this->__processParametersInString(trim($this->dsParamNEGATEPARAM), $this->_env, false) != '' ) { $this->_negate_result = true; // don't output any XML $this->dsParamPARAMOUTPUT = null; // don't output any parameters $this->dsParamINCLUDEDELEMENTS = null; // don't query any fields in this section return; } $this->_param_output_only = ((!isset($this->dsParamINCLUDEDELEMENTS) || !is_array($this->dsParamINCLUDEDELEMENTS) || empty($this->dsParamINCLUDEDELEMENTS)) && !isset($this->dsParamGROUP)); if (isset($this->dsParamREDIRECTONEMPTY) && $this->dsParamREDIRECTONEMPTY == 'yes' && $this->_force_empty_result) { throw new FrontendPageNotFoundException; } } /** * This function will parse a string (usually a URL) and fully evaluate any * parameters (defined by {$param}) to return the absolute string value. * * @since Symphony 2.3 * @param string $url * The string (usually a URL) that contains the parameters (or doesn't) * @return string * The parsed URL */ public function parseParamURL($url = null) { if (!isset($url)) { return null; } // urlencode parameters $params = array(); if (preg_match_all('@{([^}]+)}@i', $url, $matches, PREG_SET_ORDER)) { foreach ($matches as $m) { $params[$m[1]] = array( 'param' => preg_replace('/:encoded$/', null, $m[1]), 'encode' => preg_match('/:encoded$/', $m[1]) ); } } foreach ($params as $key => $info) { $replacement = $this->__processParametersInString($info['param'], $this->_env, false); if ($info['encode'] == true) { $replacement = urlencode($replacement); } $url = str_replace("{{$key}}", $replacement, $url); } return $url; } /** * This function will replace any parameters in a string with their value. * Parameters are defined by being prefixed by a `$` character. In certain * situations, the parameter will be surrounded by `{}`, which Symphony * takes to mean, evaluate this parameter to a value, other times it will be * omitted which is usually used to indicate that this parameter exists * * @param string $value * The string with the parameters that need to be evaluated * @param array $env * The environment variables from the Frontend class which includes * any params set by Symphony or Events or by other Datasources * @param boolean $includeParenthesis * Parameters will sometimes not be surrounded by `{}`. If this is the case * setting this parameter to false will make this function automatically add * them to the parameter. By default this is true, which means all parameters * in the string already are surrounded by `{}` * @param boolean $escape * If set to true, the resulting value will passed through `urlencode` before * being returned. By default this is `false` * @return string * The string with all parameters evaluated. If a parameter is not found, it will * not be replaced and remain in the `$value`. */ public function __processParametersInString($value, array $env, $includeParenthesis = true, $escape = false) { if (trim($value) == '') { return null; } if (!$includeParenthesis) { $value = '{'.$value.'}'; } if (preg_match_all('@{([^}]+)}@i', $value, $matches, PREG_SET_ORDER)) { foreach ($matches as $match) { list($source, $cleaned) = $match; $replacement = null; $bits = preg_split('/:/', $cleaned, -1, PREG_SPLIT_NO_EMPTY); foreach ($bits as $param) { if ($param{0} != '$') { $replacement = $param; break; } $param = trim($param, '$'); $replacement = Datasource::findParameterInEnv($param, $env); if (is_array($replacement)) { $replacement = array_map(array('Datasource', 'escapeCommas'), $replacement); if (count($replacement) > 1) { $replacement = implode(',', $replacement); } else { $replacement = end($replacement); } } if (!empty($replacement)) { break; } } if ($escape == true) { $replacement = urlencode($replacement); } $value = str_replace($source, $replacement, $value); } } return $value; } /** * Using regexp, this escapes any commas in the given string * * @param string $string * The string to escape the commas in * @return string */ public static function escapeCommas($string) { return preg_replace('/(?<!\\\\),/', "\\,", $string); } /** * Used in conjunction with escapeCommas, this function will remove * the escaping pattern applied to the string (and commas) * * @param string $string * The string with the escaped commas in it to remove * @return string */ public static function removeEscapedCommas($string) { return preg_replace('/(?<!\\\\)\\\\,/', ',', $string); } /** * Parameters can exist in three different facets of Symphony; in the URL, * in the parameter pool or as an Symphony param. This function will attempt * to find a parameter in those three areas and return the value. If it is not found * null is returned * * @param string $needle * The parameter name * @param array $env * The environment variables from the Frontend class which includes * any params set by Symphony or Events or by other Datasources * @return mixed * If the value is not found, null, otherwise a string or an array is returned */ public static function findParameterInEnv($needle, $env) { if (isset($env['env']['url'][$needle])) { return $env['env']['url'][$needle]; } if (isset($env['env']['pool'][$needle])) { return $env['env']['pool'][$needle]; } if (isset($env['param'][$needle])) { return $env['param'][$needle]; } return null; } } require_once TOOLKIT . '/data-sources/class.datasource.author.php'; require_once TOOLKIT . '/data-sources/class.datasource.section.php'; require_once TOOLKIT . '/data-sources/class.datasource.static.php'; require_once TOOLKIT . '/data-sources/class.datasource.dynamic_xml.php'; require_once TOOLKIT . '/data-sources/class.datasource.navigation.php';
jdsimcoe/symphony-boilerplate
symphony/lib/toolkit/class.datasource.php
PHP
mit
19,238
#include <cstdio> #include <cstring> #include <cmath> #include <algorithm> using namespace std; const double EPS = 1e-9; inline char DBLCMP(double d) { if (fabs(d) < EPS) return 0; return d>0 ? 1 : -1; } struct spoint { double x, y, z; spoint() {} spoint(double xx, double yy, double zz): x(xx), y(yy), z(zz) {} void read() {scanf("%lf%lf%lf", &x, &y, &z);} }; spoint operator - (const spoint &v1, const spoint &v2) {return spoint(v1.x-v2.x, v1.y-v2.y, v1.z-v2.z);} double dot(const spoint &v1, const spoint &v2) {return v1.x*v2.x+v1.y*v2.y+v1.z*v2.z;} double norm(const spoint &v) {return sqrt(v.x*v.x+v.y*v.y+v.z*v.z);} double dis(const spoint &p1, const spoint &p2) {return norm(p2-p1);} spoint c, n, s, v, p; double r, t1, t2, i, j, k; //ax+b=0 //0 for no solution, 1 for one solution, 2 for infinitive solution char lneq(double a, double b, double &x) { if (DBLCMP(a) == 0) { if (DBLCMP(b) == 0) return 2; return 0; } x = -b/a; return 1; } //ax^2+bx+c=0, a!=0 //0 for no solution, 1 for one solution, 2 for 2 solutions //x1 <= x2 char qdeq(double a, double b, double c, double &x1, double &x2) { double delta = b*b-4*a*c; if (delta < 0) return 0; x1 = (-b+sqrt(delta))/(2*a); x2 = (-b-sqrt(delta))/(2*a); if (x1 > x2) swap(x1, x2); return DBLCMP(delta) ? 2 : 1; } int main() { c.read(); n.read(); scanf("%lf", &r); //printf("##%f\n", dis(spoint(0,0,0), spoint(1,1,1))); s.read(); v.read(); i = -5.0*n.z; j = dot(n, v); k = dot(n, s-c); if (DBLCMP(i)==0) { char sta = lneq(j, k, t1); if (sta==0 || sta==2 || DBLCMP(t1) <= 0) { puts("MISSED"); return 0; } p.x = s.x+v.x*t1; p.y = s.y+v.y*t1; p.z = s.z+v.z*t1-5.0*t1*t1; if (DBLCMP(dis(p, c)-r) < 0) { puts("HIT"); return 0; } puts("MISSED"); return 0; } if (!qdeq(i, j, k, t1, t2)) { puts("MISSED"); return 0; } if (DBLCMP(t1) > 0) { p.x = s.x+v.x*t1; p.y = s.y+v.y*t1; p.z = s.z+v.z*t1-5.0*t1*t1; if (DBLCMP(dis(p, c)-r) < 0) { puts("HIT"); return 0; } } if (DBLCMP(t2) > 0) { p.x = s.x+v.x*t2; p.y = s.y+v.y*t2; p.z = s.z+v.z*t2-5.0*t2*t2; if (DBLCMP(dis(p, c)-r) < 0) { puts("HIT"); return 0; } } puts("MISSED"); return 0; }
jffifa/algo-solution
ural/1093.cpp
C++
mit
2,211
<?php /** * Examples of ShareCouners usage * @author Dominik Bułaj <dominik@bulaj.com> */ include '../src/SharesCounter.php'; include '../src/Networks.php'; include '../src/Exception.php'; $url = 'http://www.huffingtonpost.com'; // 1. return shares from Facebook and Twitter $shares = new \SharesCounter\SharesCounter($url); $counts = $shares->getShares([\SharesCounter\Networks::NETWORK_FACEBOOK, \SharesCounter\Networks::NETWORK_TWITTER]); var_dump($counts); // 2. return shares from all available networks $shares = new \SharesCounter\SharesCounter($url); $counts = $shares->getShares([]); var_dump($counts); // 3. return shares from disabled by default network $url = 'http://www.moy-rebenok.ru'; $shares = new \SharesCounter\SharesCounter($url); $counts = $shares->getShares([\SharesCounter\Networks::NETWORK_VK, \SharesCounter\Networks::NETWORK_ODNOKLASSNIKI]); var_dump($counts); // 4. wykop.pl $url = 'http://pokazywarka.pl/margaryna/'; $shares = new \SharesCounter\SharesCounter($url); $counts = $shares->getShares([\SharesCounter\Networks::NETWORK_WYKOP]); var_dump($counts); // 4. helper method - return list of available networks $networks = new \SharesCounter\Networks(); $availableNetworks = $networks->getAvailableNetworks(); var_export($availableNetworks);
dominikbulaj/shares-counter-php
examples/index.php
PHP
mit
1,282
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateCharactersLangTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { // Create the characters_lang table Schema::create('characters_lang', function($table) { $default_locale = \Config::get('app.locale'); $locales = \Config::get('app.locales', array($default_locale)); $table->increments('id'); $table->mediumInteger('character_id'); $table->string('firstname')->nullable(); $table->string('lastname')->nullable(); $table->string('nickname')->nullable(); $table->string('overview')->nullable(); $table->enum('locale', $locales); $table->softDeletes(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { // Drop the characters_lang table Schema::dropIfExists('characters_lang'); } }
Truemedia/regeneration-character
src/database/migrations/2015_05_16_174527_create_characters_lang_table.php
PHP
mit
981
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'><head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta> <title>124-10-7.smi.png.html</title> </head> <body>ID124-10-7<br/> <img border="0" src="124-10-7.smi.png" alt="124-10-7.smi.png"></img><br/> <br/> <table border="1"> <tr> <td></td><td>ID</td><td>Formula</td><td>FW</td><td>DSSTox_CID</td><td>DSSTox_RID</td><td>DSSTox_GSID</td><td>DSSTox_FileID_Sort</td><td>TS_ChemName</td><td>TS_ChemName_Synonyms</td><td>TS_CASRN</td><td>CASRN_ChemName_Relationship</td><td>TS_Description</td><td>ChemNote</td><td>STRUCTURE_Shown</td><td>STRUCTURE_Formula</td><td>STRUCTURE_MW</td><td>STRUCTURE_ChemType</td><td>STRUCTURE_DefinedOrganicForm</td><td>STRUCTURE_IUPAC</td><td>STRUCTURE_SMILES</td><td>STRUCTURE_SMILES_Desalt</td><td>Substance_modify_yyyymmdd</td></tr> <tr> <td>124-10-7</td><td>4886</td><td>C15H30O2</td><td>242.3975</td><td>7019</td><td>78281</td><td>27019</td><td>2964</td><td>Methyl tetradecanoate</td><td>Methyl tetradecanoate (Tetradecanoic acid, methyl ester) (Methyl myristate)</td><td>124-10-7</td><td>primary</td><td>single chemical compound</td><td></td><td>tested chemical</td><td>C15H30O2</td><td>242.3975</td><td>defined organic</td><td>parent</td><td>methyl tetradecanoate</td><td>O=C(CCCCCCCCCCCCC)OC</td><td>O=C(CCCCCCCCCCCCC)OC</td><td>20080429</td></tr> </table> <br/><br/><font size="-2">(Page generated on Wed Sep 17 03:57:12 2014 by <a href="http://www.embl.de/~gpau/hwriter/index.html">hwriter</a> 1.3)</font><br/> </body></html>
andrewdefries/ToxCast
Figure3/Tox21_nnm/WorkHere/124-10-7.smi.png.html
HTML
mit
1,675
import React, {Component} from 'react'; import {Typeahead} from 'react-bootstrap-typeahead'; import {inject, observer} from 'mobx-react'; import {action, toJS, autorunAsync} from 'mobx'; import myClient from '../agents/client' require('react-bootstrap-typeahead/css/ClearButton.css'); require('react-bootstrap-typeahead/css/Loader.css'); require('react-bootstrap-typeahead/css/Token.css'); require('react-bootstrap-typeahead/css/Typeahead.css'); @inject('controlsStore', 'designStore') @observer export default class EroTypeahead extends Component { constructor(props) { super(props); } state = { options: [] }; // this will keep updating the next -ERO options as the ERO changes; disposeOfEroOptionsUpdate = autorunAsync('ero options update', () => { let ep = this.props.controlsStore.editPipe; let submitEro = toJS(ep.ero.hops); // keep track of the last hop; if we've reached Z we shouldn't keep going let lastHop = ep.a; if (ep.ero.hops.length > 0) { lastHop = ep.ero.hops[ep.ero.hops.length - 1]; } else { // if there's _nothing_ in our ERO then ask for options from pipe.a submitEro.push(ep.a); } // if this is the last hop, don't provide any options if (lastHop === ep.z) { this.setState({options: []}); return; } myClient.submit('POST', '/api/pce/nextHopsForEro', submitEro) .then( action((response) => { let nextHops = JSON.parse(response); if (nextHops.length > 0) { let opts = []; nextHops.map(h => { let entry = { id: h.urn, label: h.urn + ' through ' + h.through + ' to ' + h.to, through: h.through, to: h.to }; opts.push(entry); }); this.setState({options: opts}); } })); }, 500); componentWillUnmount() { this.disposeOfEroOptionsUpdate(); } onTypeaheadSelection = selection => { if (selection.length === 0) { return; } let wasAnOption = false; let through = ''; let urn = ''; let to = ''; this.state.options.map(opt => { if (opt.label === selection) { wasAnOption = true; through = opt.through; urn = opt.id; to = opt.to; } }); if (wasAnOption) { let ep = this.props.controlsStore.editPipe; let ero = []; ep.manual.ero.map(e => { ero.push(e); }); ero.push(through); ero.push(urn); ero.push(to); this.props.controlsStore.setParamsForEditPipe({ ero: { hops: ero }, manual: {ero: ero} }); this.typeAhead.getInstance().clear(); } }; render() { return ( <Typeahead minLength={0} ref={(ref) => { this.typeAhead = ref; }} placeholder='choose from selection' options={this.state.options} onInputChange={this.onTypeaheadSelection} clearButton /> ); } }
haniotak/oscars-frontend
src/main/js/components/eroTypeahead.js
JavaScript
mit
3,673
'use strict'; var convert = require('./convert'), func = convert('lt', require('../lt')); func.placeholder = require('./placeholder'); module.exports = func; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL2NsaWVudC9saWIvbG9kYXNoL2ZwL2x0LmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsSUFBSSxVQUFVLFFBQVEsV0FBUixDQUFWO0lBQ0EsT0FBTyxRQUFRLElBQVIsRUFBYyxRQUFRLE9BQVIsQ0FBZCxDQUFQOztBQUVKLEtBQUssV0FBTCxHQUFtQixRQUFRLGVBQVIsQ0FBbkI7QUFDQSxPQUFPLE9BQVAsR0FBaUIsSUFBakIiLCJmaWxlIjoibHQuanMiLCJzb3VyY2VzQ29udGVudCI6WyJ2YXIgY29udmVydCA9IHJlcXVpcmUoJy4vY29udmVydCcpLFxuICAgIGZ1bmMgPSBjb252ZXJ0KCdsdCcsIHJlcXVpcmUoJy4uL2x0JykpO1xuXG5mdW5jLnBsYWNlaG9sZGVyID0gcmVxdWlyZSgnLi9wbGFjZWhvbGRlcicpO1xubW9kdWxlLmV4cG9ydHMgPSBmdW5jO1xuIl19
justin-lai/hackd.in
compiled/client/lib/lodash/fp/lt.js
JavaScript
mit
778
<?php /** * UserAccount * * This class has been auto-generated by the Doctrine ORM Framework * * @package blueprint * @subpackage model * @author Your name here * @version SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $ */ class UserAccount extends BaseUserAccount { }
zenkovnick/pfr
lib/model/doctrine/UserAccount.class.php
PHP
mit
299
# Rounded Button Twitch Chat ![alt text](https://raw.githubusercontent.com/WolfgangAxel/Random-Projects/master/Streaming/RoundButtonExample.png) This CSS file overrides the Twitch chat popout window to make the chat slightly more visually appealing. It was created to be used with the OBS plugin Linux Browser, and presumably will work with the default Browser source for Mac and Windows. ## Instructions For Use 1. Add a (Linux) Browser source to a scene 2. Set the URL to `https://www.twitch.tv/{yourchannel}/chat` 3. Select this CSS file for the custom CSS 4. Adjust page size, zoom, and crop until only the chat area is visible 5. Add a Chroma Key filter 6. Set the Key Color Type to Custom and change the Key Color to `#123123` 7. Adjust the similarity, smoothness, and key color spillreduction to your liking (1, 35, 100 are what I found to work best) 8. Sit back and enjoy! ## Notes ### Dark Theme Check the comments in the file for recommended hex values for a dark theme! ### Badges To add badges back into the chat, simply comment out or delete the last section of the file: .badges { /* Hide badges */ position:absolute!important; visibility:hidden; } ### Browser Sizing What I found works well is 150% zoom and a minimum width of 450px. From here, add a crop filter with 76px top and 168px bottom. This should perfectly frame your chat without losing any space.
WolfgangAxel/Random-Projects
Streaming/Rounded Button Twitch Chat/README.md
Markdown
mit
1,418
purescript-three ================ Purescript bindings for Threejs # Build purescript-three ``` bower install pulp build bower link ``` # Build examples ``` cd examples/ bower link purescript-three pulp browserify --main Examples.CircleToSquare --to output/circleToSquare.js pulp browserify --main Examples.LineArray --to output/lineArray.js pulp browserify --main Examples.MotionStretch --to output/motionStretch.js pulp browserify --main Examples.SimpleCube --to output/simpleCube.js pulp browserify --main Examples.SimpleLine --to output/simpleLine.js open resources/*.html // in your favorite browser ```
anthoq88/purescript-three
README.md
Markdown
mit
615
TOP_DIR = ../.. LIB_DIR = lib/ DEPLOY_RUNTIME ?= /kb/runtime TARGET ?= /kb/deployment include $(TOP_DIR)/tools/Makefile.common SPEC_FILE = handle_mngr.spec SERVICE_NAME = HandleMngr SERVICE_CAPS = HandleMngr SERVICE_PORT = 9001 SERVICE_DIR = handle_mngr SERVICE_CONFIG = HandleMngr ifeq ($(SELF_URL),) SELF_URL = http://localhost:$(SERVICE_PORT) endif SERVICE_PSGI = $(SERVICE_NAME).psgi TPAGE_ARGS = --define kb_runas_user=$(SERVICE_USER) --define kb_top=$(TARGET) --define kb_runtime=$(DEPLOY_RUNTIME) --define kb_service_name=$(SERVICE_NAME) --define kb_service_config_stanza=$(SERVICE_CONFIG) --define kb_service_dir=$(SERVICE_DIR) --define kb_service_port=$(SERVICE_PORT) --define kb_psgi=$(SERVICE_PSGI) # to wrap scripts and deploy them to $(TARGET)/bin using tools in # the dev_container. right now, these vars are defined in # Makefile.common, so it's redundant here. TOOLS_DIR = $(TOP_DIR)/tools WRAP_PERL_TOOL = wrap_perl WRAP_PERL_SCRIPT = bash $(TOOLS_DIR)/$(WRAP_PERL_TOOL).sh SRC_PERL = $(wildcard scripts/*.pl) # You can change these if you are putting your tests somewhere # else or if you are not using the standard .t suffix CLIENT_TESTS = $(wildcard client-tests/*.t) SCRIPTS_TESTS = $(wildcard script-tests/*.t) SERVER_TESTS = $(wildcard server-tests/*.t) # This is a very client-centric view of release engineering. # We assume our primary product for the community is the client # libraries, command line interfaces, and the related documentation # from which specific science applications can be built. # # A service is composed of a client and a server, each of which # should be independently deployable. Clients are composed of # an application programming interface (API) and a command line # interface (CLI). In our make targets, deploy-service deploys # the server, deploy-client deploys the application # programming interface libraries, and deploy-scripts deploys # the command line interface (usually scripts written in a # scripting language but java executables also qualify), and the # deploy target would be equivelant to deploying a service (client # libs, scripts, and server). # # Because the deployment of the server side code depends on the # specific software module being deployed, the strategy needs # to be one that leaves this decision to the module developer. # This is done by having the deploy target depend on the # deploy-service target. The module developer who chooses for # good reason not to deploy the server with the client simply # manages this dependancy accordingly. One option is to have # a deploy-service target that does nothing, the other is to # remove the dependancy from the deploy target. # # A smiliar naming convention is used for tests. default: # Distribution Section # # This section deals with the packaging of source code into a # distributable form. This is different from a deployable form # as our deployments tend to be kbase specific. To create a # distribution, we have to consider the distribution mechanisms. # For starters, we will consider cpan style packages for perl # code, we will consider egg for python, npm for javascript, # and it is not clear at this time what is right for java. # # In all cases, it is important not to implement into these # targets the actual distribution. What these targets deal # with is creating the distributable object (.tar.gz, .jar, # etc) and placing it in the top level directory of the module # distrubution directory. # # Use <module_name>/distribution as the top level distribution # directory dist: dist-cpan dist-egg dist-npm dist-java dist-r dist-cpan: dist-cpan-client dist-cpan-service dist-egg: dist-egg-client dist-egg-service # In this case, it is not clear what npm service would mean, # unless we are talking about a service backend implemented # in javascript, which I can imagine happing. So the target # is here, even though we don't have support for javascript # on the back end of the compiler at this time. dist-npm: dist-npm-client dist-npm-service dist-java: dist-java-client dist-java-service # in this case, I'm using the word client just for consistency # sake. What we mean by client is an R library. At this time # the meaning of a r-service is not understood. It can be # added at a later time if there is a good reason. dist-r: dist-r-client dist-cpan-client: echo "cpan client distribution not supported" dist-cpan-service: echo "cpan service distribution not supported" dist-egg-client: echo "egg client distribution not supported" dist-egg-service: echo "egg service distribution not supported" dist-npm-client: echo "npm client distribution not supported" dist-npm-service: echo "npm service distribution not supported" dist-java-client: echo "java client distribution not supported" dist-java-service: echo "java service distribuiton not supported" dist-r-client: echo "r client lib distribution not supported" # Test Section test: test-client test-scripts test-service @echo "running client and script tests" # test-all is deprecated. # test-all: test-client test-scripts test-service # # test-client: This is a test of a client library. If it is a # client-server module, then it should be run against a running # server. You can say that this also tests the server, and I # agree. You can add a test-service dependancy to the test-client # target if it makes sense to you. This test example assumes there is # already a tested running server. test-client: # run each test for t in $(CLIENT_TESTS) ; do \ if [ -f $$t ] ; then \ $(DEPLOY_RUNTIME)/bin/perl $$t ; \ if [ $$? -ne 0 ] ; then \ exit 1 ; \ fi \ fi \ done # test-scripts: A script test should test the command line scripts. If # the script is a client in a client-server architecture, then there # should be tests against a running server. You can add a test-service # dependency to the test-client target. You could also add a # deploy-service and start-server dependancy to the test-scripts # target if it makes sense to you. Future versions of the makefiles # for services will move in this direction. test-scripts: # run each test for t in $(SCRIPT_TESTS) ; do \ if [ -f $$t ] ; then \ $(DEPLOY_RUNTIME)/bin/perl $$t ; \ if [ $$? -ne 0 ] ; then \ exit 1 ; \ fi \ fi \ done # test-service: A server test should not rely on the client libraries # or scripts--you should not have a test-service target that depends # on the test-client or test-scripts targets. Otherwise, a circular # dependency graph could result. test-service: # run each test for t in $(SERVER_TESTS) ; do \ if [ -f $$t ] ; then \ $(DEPLOY_RUNTIME)/bin/perl $$t ; \ if [ $$? -ne 0 ] ; then \ exit 1 ; \ fi \ fi \ done # Deployment: # # We are assuming our primary products to the community are # client side application programming interface libraries and a # command line interface (scripts). The deployment of client # artifacts should not be dependent on deployment of a server, # although we recommend deploying the server code with the # client code when the deploy target is executed. If you have # good reason not to deploy the server at the same time as the # client, just delete the dependancy on deploy-service. It is # important to note that you must have a deploy-service target # even if there is no server side code to deploy. deploy: deploy-client deploy-service # deploy-all deploys client *and* server. This target is deprecated # and should be replaced by the deploy target. deploy-all: deploy-client deploy-service # deploy-client should deploy the client artifacts, mainly # the application programming interface libraries, command # line scripts, and associated reference documentation. deploy-client: deploy-libs deploy-scripts deploy-docs # The deploy-libs and deploy-scripts targets are used to recognize # and delineate the client types, mainly a set of libraries that # implement an application programming interface and a set of # command line scripts that provide command-based execution of # individual API functions and aggregated sets of API functions. deploy-libs: build-libs rsync --exclude '*.bak*' -arv lib/. $(TARGET)/lib/. # Deploying scripts needs some special care. They need to run # in a certain runtime environment. Users should not have # to modify their user environments to run kbase scripts, other # than just sourcing a single user-env script. The creation # of this user-env script is the responsibility of the code # that builds all the kbase modules. In the code below, we # run a script in the dev_container tools directory that # wraps perl scripts. The name of the perl wrapper script is # kept in the WRAP_PERL_SCRIPT make variable. This script # requires some information that is passed to it by way # of exported environment variables in the bash script below. # # What does it mean to wrap a perl script? To wrap a perl # script means that a bash script is created that sets # all required environment variables and then calls the perl # script using the perl interperter in the kbase runtime. # For this to work, both the actual script and the newly # created shell script have to be deployed. When a perl # script is wrapped, it is first copied to TARGET/plbin. # The shell script can now be created because the necessary # environment variables are known and the location of the # script is known. deploy-scripts: export KB_TOP=$(TARGET); \ export KB_RUNTIME=$(DEPLOY_RUNTIME); \ export KB_PERL_PATH=$(TARGET)/lib bash ; \ for src in $(SRC_PERL) ; do \ basefile=`basename $$src`; \ base=`basename $$src .pl`; \ echo install $$src $$base ; \ cp $$src $(TARGET)/plbin ; \ $(WRAP_PERL_SCRIPT) "$(TARGET)/plbin/$$basefile" $(TARGET)/bin/$$base ; \ done # Deploying a service refers to to deploying the capability # to run a service. Becuase service code is often deployed # as part of the libs, meaning service code gets deployed # when deploy-libs is called, the deploy-service target is # generally concerned with the service start and stop scripts. # The deploy-cfg target is defined in the common rules file # located at $TOP_DIR/tools/Makefile.common.rules and included # at the end of this file. deploy-service: deploy-cfg mkdir -p $(TARGET)/services/$(SERVICE_DIR) $(TPAGE) $(TPAGE_ARGS) service/start_service.tt > $(TARGET)/services/$(SERVICE_DIR)/start_service chmod +x $(TARGET)/services/$(SERVICE_DIR)/start_service $(TPAGE) $(TPAGE_ARGS) service/stop_service.tt > $(TARGET)/services/$(SERVICE_DIR)/stop_service chmod +x $(TARGET)/services/$(SERVICE_DIR)/stop_service $(TPAGE) $(TPAGE_ARGS) service/upstart.tt > service/$(SERVICE_NAME).conf chmod +x service/$(SERVICE_NAME).conf $(TPAGE) $(TPAGE_ARGS) service/constants.tt > $(TARGET)/lib/Bio/KBase/HandleMngrConstants.pm echo "done executing deploy-service target" deploy-upstart: deploy-service -cp service/$(SERVICE_NAME).conf /etc/init/ echo "done executing deploy-upstart target" # Deploying docs here refers to the deployment of documentation # of the API. We'll include a description of deploying documentation # of command line interface scripts when we have a better understanding of # how to standardize and automate CLI documentation. deploy-docs: build-docs -mkdir -p $(TARGET)/services/$(SERVICE_DIR)/webroot/. cp docs/*.html $(TARGET)/services/$(SERVICE_DIR)/webroot/. # The location of the Client.pm file depends on the --client param # that is provided to the compile_typespec command. The # compile_typespec command is called in the build-libs target. build-docs: compile-docs -mkdir -p docs pod2html --infile=lib/Bio/KBase/$(SERVICE_NAME)/$(SERVICE_CAPS)Client.pm --outfile=docs/$(SERVICE_NAME).html # Use the compile-docs target if you want to unlink the generation of # the docs from the generation of the libs. Not recommended, but there # could be a reason for it that I'm not seeing. # The compile-docs target should depend on build-libs so that we are # assured of having a set of documentation that is based on the latest # type spec. compile-docs: build-libs # build-libs should be dependent on the type specification and the # type compiler. Building the libs in this way means that you don't # need to put automatically generated code in a source code version # control repository (e.g., cvs, git). It also ensures that you always # have the most up-to-date libs and documentation if your compile-docs # target depends on the compiled libs. build-libs: kb-sdk compile $(SPEC_FILE) \ --out $(LIB_DIR) \ --plpsginame $(SERVICE_CAPS).psgi \ --plimplname Bio::KBase::$(SERVICE_CAPS)::$(SERVICE_CAPS)Impl \ --plsrvname Bio::KBase::$(SERVICE_CAPS)::$(SERVICE_CAPS)Server \ --plclname Bio::KBase::$(SERVICE_CAPS)::$(SERVICE_CAPS)Client \ --pyclname biokbase/$(SERVICE_CAPS)/Client \ --jsclname javascript/$(SERVICE_CAPS)/Client \ --url $(SELF_URL) # the Makefile.common.rules contains a set of rules that can be used # in this setup. Because it is included last, it has the effect of # shadowing any targets defined above. So lease be aware of the # set of targets in the common rules file. include $(TOP_DIR)/tools/Makefile.common.rules
kbase/handle_mngr
Makefile
Makefile
mit
13,184
<?php use PDFfiller\OAuth2\Client\Provider\Token; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $e = Token::one($provider, 3329); dd($e);
pdffiller/pdffiller-php-api-client
examples/token/3_get_token.php
PHP
mit
164
package sql.fredy.sqltools; /** XLSExport exports the result of a query into a XLS-file. To do this it is using HSSF from the Apache POI Project: http://jakarta.apache.org/poi Version 1.0 Date 7. aug. 2003 Author Fredy Fischer XLSExport is part of the Admin-Suite Once instantiated there are the following steps to go to get a XLS-file out of a query XLSExport xe = new XLSExport(java.sql.Connection con) xe.setQuery(java.lang.String query) please set herewith the the query to get its results as XLS-file int xe.createXLS(java.lang.String fileName) this will then create the XLS-File. If this file already exists, it will be overwritten! it returns the number of rows written to the File 2015-11-16 Creating an additional Worksheet containing the SQL-Query Admin is a Tool around SQL to do basic jobs for DB-Administrations, like: - create/ drop tables - create indices - perform sql-statements - simple form - a guided query and a other usefull things in DB-arena Copyright (c) 2017 Fredy Fischer, sql@hulmen.ch Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import sql.fredy.share.t_connect; import java.io.InputStream; import java.io.IOException; import java.io.ByteArrayInputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.sql.*; import java.util.logging.*; import java.util.Date; import org.apache.poi.xssf.usermodel.*; import org.apache.poi.hssf.record.*; import org.apache.poi.hssf.model.*; import org.apache.poi.hssf.usermodel.*; import org.apache.poi.hssf.util.*; import java.util.ArrayList; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.CreationHelper; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.streaming.SXSSFSheet; import org.apache.poi.xssf.streaming.SXSSFWorkbook; public class XLSExport { private Logger logger; Connection con = null; /** * Get the value of con. * * @return value of con. */ public Connection getCon() { return con; } /** * Set the value of con. * * @param v Value to assign to con. */ public void setCon(Connection v) { this.con = v; } String query=null; /** * Get the value of query. * * @return value of query. */ public String getQuery() { return query; } /** * Set the value of query. * * @param v Value to assign to query. */ public void setQuery(String v) { this.query = v; } java.sql.SQLException exception; /** * Get the value of exception. * * @return value of exception. */ public java.sql.SQLException getException() { return exception; } /** * Set the value of exception. * * @param v Value to assign to exception. */ public void setException(java.sql.SQLException v) { this.exception = v; } private PreparedStatement pstmt = null; /* is this file xlsx or xls? we detect this out of the filename extension */ private boolean xlsx = false; private void checkXlsx(String fileName) { String[] extension = fileName.split("\\."); int l = extension.length - 1; String fileType = extension[l].toLowerCase(); if ("xlsx".equals(fileType)) { setXlsx(true); } } /* we need to check, if the extension of the Filename is either xls or xlsx if not, we set to xlsx as default */ private String fixFileName(String f) { String prefix = "", postfix = ""; String fixed = f; int i = f.lastIndexOf("."); // no postfix at all set if (i < 0) { fixed = f + ".xlsx"; } else { prefix = f.substring(0, i); postfix = f.substring(i + 1); logger.log(Level.FINE, "Prefix: " + prefix + " Postfix: " + postfix); if ((postfix.equalsIgnoreCase("xlsx")) || (postfix.equalsIgnoreCase("xls"))) { // nothing to do } else { postfix = "xlsx"; } fixed = prefix + "." + postfix; } logger.log(Level.INFO, "Filename: " + fixed); return fixed; } /** * Create the XLS-File named fileName * * @param fileName is the Name (incl. Path) of the XLS-file to create * * */ public int createXLS(String fileName) { // I need to have a query to process if ((getQuery() == null) && (getPstmt() == null)) { logger.log(Level.WARNING, "Need to have a query to process"); return 0; } // I also need to have a file to write into if (fileName == null) { logger.log(Level.WARNING, "Need to know where to write into"); return 0; } fileName = fixFileName(fileName); checkXlsx(fileName); // I need to have a connection to the RDBMS if (getCon() == null) { logger.log(Level.WARNING, "Need to have a connection to process"); return 0; } //Statement stmt = null; ResultSet resultSet = null; ResultSetMetaData rsmd = null; try { // first we have to create the Statement if (getPstmt() == null) { pstmt = getCon().prepareStatement(getQuery()); } //stmt = getCon().createStatement(); } catch (SQLException sqle1) { setException(sqle1); logger.log(Level.WARNING, "Can not create Statement. Message: " + sqle1.getMessage().toString()); return 0; } logger.log(Level.FINE, "FileName: " + fileName); logger.log(Level.FINE, "Query : " + getQuery()); logger.log(Level.FINE, "Starting export..."); // create an empty sheet Workbook wb; Sheet sheet; Sheet sqlsheet; CreationHelper createHelper = null; //XSSFSheet xsheet; //HSSFSheet sheet; if (isXlsx()) { wb = new SXSSFWorkbook(); createHelper = wb.getCreationHelper(); } else { wb = new HSSFWorkbook(); createHelper = wb.getCreationHelper(); } sheet = wb.createSheet("Data Export"); // create a second sheet just containing the SQL Statement sqlsheet = wb.createSheet("SQL Statement"); Row sqlrow = sqlsheet.createRow(0); Cell sqltext = sqlrow.createCell(0); try { if ( getQuery() != null ) { sqltext.setCellValue(getQuery()); } else { sqltext.setCellValue(pstmt.toString()); } } catch (Exception lex) { } CellStyle style = wb.createCellStyle(); style.setWrapText(true); sqltext.setCellStyle(style); Row r = null; int row = 0; // row number int col = 0; // column number int columnCount = 0; try { //resultSet = stmt.executeQuery(getQuery()); resultSet = pstmt.executeQuery(); logger.log(Level.FINE, "query executed"); } catch (SQLException sqle2) { setException(sqle2); logger.log(Level.WARNING, "Can not execute query. Message: " + sqle2.getMessage().toString()); return 0; } // create Header in XLS-file ArrayList<String> head = new ArrayList(); try { rsmd = resultSet.getMetaData(); logger.log(Level.FINE, "Got MetaData of the resultset"); columnCount = rsmd.getColumnCount(); logger.log(Level.FINE, Integer.toString(columnCount) + " Columns in this resultset"); r = sheet.createRow(row); // titlerow if ((!isXlsx()) && (columnCount > 255)) { columnCount = 255; } for (int i = 0; i < columnCount; i++) { // we create the cell Cell cell = r.createCell(col); // set the value of the cell cell.setCellValue(rsmd.getColumnName(i + 1)); head.add(rsmd.getColumnName(i + 1)); // then we align center CellStyle cellStyle = wb.createCellStyle(); cellStyle.setAlignment(CellStyle.ALIGN_CENTER); // now we make it bold //HSSFFont f = wb.createFont(); Font headerFont = wb.createFont(); headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD); cellStyle.setFont(headerFont); //cellStyle.setFont(f); // adapt this font to the cell cell.setCellStyle(cellStyle); col++; } } catch (SQLException sqle3) { setException(sqle3); logger.log(Level.WARNING, "Can not create XLS-Header. Message: " + sqle3.getMessage().toString()); return 0; } // looping the resultSet int wbCounter = 0; try { while (resultSet.next()) { // this is the next row col = 0; // put column counter back to 0 to start at the next row row++; // next row // create a new sheet if more then 60'000 Rows and xls file if ((!isXlsx()) && (row % 65530 == 0)) { wbCounter++; row = 0; sheet = wb.createSheet("Data Export " + Integer.toString(wbCounter)); logger.log(Level.INFO, "created a further page because of a huge amount of data"); // create the head r = sheet.createRow(row); // titlerow for (int i = 0; i < head.size(); i++) { // we create the cell Cell cell = r.createCell(col); // set the value of the cell cell.setCellValue((String) head.get(i)); // then we align center CellStyle cellStyle = wb.createCellStyle(); cellStyle.setAlignment(CellStyle.ALIGN_CENTER); // now we make it bold //HSSFFont f = wb.createFont(); Font headerFont = wb.createFont(); headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD); cellStyle.setFont(headerFont); //cellStyle.setFont(f); // adapt this font to the cell cell.setCellStyle(cellStyle); col++; } row++; } try { r = sheet.createRow(row); } catch (Exception e) { logger.log(Level.WARNING, "Error while creating row number " + row + " " + e.getMessage()); wbCounter++; row = 0; sheet = wb.createSheet("Data Export " + Integer.toString(wbCounter)); logger.log(Level.WARNING, "created a further page in the hope it helps..."); // create the head r = sheet.createRow(row); // titlerow for (int i = 0; i < head.size(); i++) { // we create the cell Cell cell = r.createCell(col); // set the value of the cell cell.setCellValue((String) head.get(i)); // then we align center CellStyle cellStyle = wb.createCellStyle(); cellStyle.setAlignment(CellStyle.ALIGN_CENTER); // now we make it bold //HSSFFont f = wb.createFont(); Font headerFont = wb.createFont(); headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD); cellStyle.setFont(headerFont); //cellStyle.setFont(f); // adapt this font to the cell cell.setCellStyle(cellStyle); col++; } row++; } col = 0; // put column counter back to 0 to start at the next row String previousMessage = ""; for (int i = 0; i < columnCount; i++) { try { // depending on the type, create the cell switch (rsmd.getColumnType(i + 1)) { case java.sql.Types.INTEGER: r.createCell(col).setCellValue(resultSet.getInt(i + 1)); break; case java.sql.Types.FLOAT: r.createCell(col).setCellValue(resultSet.getFloat(i + 1)); break; case java.sql.Types.DOUBLE: r.createCell(col).setCellValue(resultSet.getDouble(i + 1)); break; case java.sql.Types.DECIMAL: r.createCell(col).setCellValue(resultSet.getFloat(i + 1)); break; case java.sql.Types.NUMERIC: r.createCell(col).setCellValue(resultSet.getFloat(i + 1)); break; case java.sql.Types.BIGINT: r.createCell(col).setCellValue(resultSet.getInt(i + 1)); break; case java.sql.Types.TINYINT: r.createCell(col).setCellValue(resultSet.getInt(i + 1)); break; case java.sql.Types.SMALLINT: r.createCell(col).setCellValue(resultSet.getInt(i + 1)); break; case java.sql.Types.DATE: // first we get the date java.sql.Date dat = resultSet.getDate(i + 1); java.util.Date date = new java.util.Date(dat.getTime()); r.createCell(col).setCellValue(date); break; case java.sql.Types.TIMESTAMP: // first we get the date java.sql.Timestamp ts = resultSet.getTimestamp(i + 1); Cell c = r.createCell(col); try { c.setCellValue(ts); // r.createCell(col).setCellValue(ts); // Date Format CellStyle cellStyle = wb.createCellStyle(); cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy/mm/dd hh:mm:ss")); c.setCellStyle(cellStyle); } catch (Exception e) { c.setCellValue(" "); } break; case java.sql.Types.TIME: // first we get the date java.sql.Time time = resultSet.getTime(i + 1); r.createCell(col).setCellValue(time); break; case java.sql.Types.BIT: boolean b1 = resultSet.getBoolean(i + 1); r.createCell(col).setCellValue(b1); break; case java.sql.Types.BOOLEAN: boolean b2 = resultSet.getBoolean(i + 1); r.createCell(col).setCellValue(b2); break; case java.sql.Types.CHAR: r.createCell(col).setCellValue(resultSet.getString(i + 1)); break; case java.sql.Types.NVARCHAR: r.createCell(col).setCellValue(resultSet.getString(i + 1)); break; case java.sql.Types.VARCHAR: try { r.createCell(col).setCellValue(resultSet.getString(i + 1)); } catch (Exception e) { r.createCell(col).setCellValue(" "); logger.log(Level.WARNING, "Exception while writing column {0} row {3} type: {1} Message: {2}", new Object[]{col, rsmd.getColumnType(i + 1), e.getMessage(), row}); } break; default: r.createCell(col).setCellValue(resultSet.getString(i + 1)); break; } } catch (Exception e) { //e.printStackTrace(); if (resultSet.wasNull()) { r.createCell(col).setCellValue(" "); } else { logger.log(Level.WARNING, "Unhandled type at column {0}, row {3} type: {1}. Filling up with blank {2}", new Object[]{col, rsmd.getColumnType(i + 1), e.getMessage(), row}); r.createCell(col).setCellValue(" "); } } col++; } } //pstmt.close(); } catch (SQLException sqle3) { setException(sqle3); logger.log(Level.WARNING, "Exception while writing data into sheet. Message: " + sqle3.getMessage().toString()); } try { // Write the output to a file FileOutputStream fileOut = new FileOutputStream(fileName); wb.write(fileOut); fileOut.close(); logger.log(Level.INFO, "File created"); logger.log(Level.INFO, "Wrote: {0} lines into XLS-File", Integer.toString(row)); } catch (Exception e) { logger.log(Level.WARNING, "Exception while writing xls-File: " + e.getMessage().toString()); } return row; } public XLSExport(Connection con) { logger = Logger.getLogger("sql.fredy.sqltools"); setCon(con); } public XLSExport() { logger = Logger.getLogger("sql.fredy.sqltools"); } public static void main(String args[]) { String host = "localhost"; String user = System.getProperty("user.name"); String schema = "%"; String database = null; String password = null; String query = null; String file = null; System.out.println("XLSExport\n" + "----------\n" + "Syntax: java sql.fredy.sqltools.XLSExport\n" + " Parameters: -h Host (default: localhost)\n" + " -u User (default: " + System.getProperty("user.name") + ")\n" + " -p Password\n" + " -q Query\n" + " -Q Filename of the file containing the Query\n" + " -d database\n" + " -f File to write into (.xls or xlsx)\n"); int i = 0; while (i < args.length) { if (args[i].equals("-h")) { i++; host = args[i]; } if (args[i].equals("-u")) { i++; user = args[i]; } if (args[i].equals("-p")) { i++; password = args[i]; } if (args[i].equals("-d")) { i++; database = args[i]; } if (args[i].equals("-q")) { i++; query = args[i]; } if (args[i].equals("-Q")) { i++; sql.fredy.io.ReadFile rf = new sql.fredy.io.ReadFile(args[i]); query = rf.getText(); } if (args[i].equals("-f")) { i++; file = args[i]; } i++; }; t_connect tc = new t_connect(host, user, password, database); XLSExport xe = new XLSExport(tc.con); xe.setQuery(query); xe.createXLS(file); tc.close(); } /** * @return the xlsx */ public boolean isXlsx() { return xlsx; } /** * @param xlsx the xlsx to set */ public void setXlsx(boolean xlsx) { this.xlsx = xlsx; } /** * @return the pstmt */ public PreparedStatement getPstmt() { return pstmt; } /** * @param pstmt the pstmt to set */ public void setPstmt(PreparedStatement pstmt) { this.pstmt = pstmt; } }
hulmen/SQLAdmin
src/fredy/sqltools/XLSExport.java
Java
mit
23,048
# -*- coding: utf-8 -*- # Copyright (c) 2016 Jérémie DECOCK (http://www.jdhp.org) # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """ TODO... """ __all__ = ['GreedyPlayer'] import random from jdhp.tictactoe.player.abstract import Player class GreedyPlayer(Player): """ TODO... """ def play(self, game, state): """ TODO... """ action_list = game.getSetOfValidActions(state) choosen_action = None # Choose actions that lead to immediate victory... for action in action_list: next_state = game.nextState(state, action, self) if game.hasWon(self, next_state): choosen_action = action break # ... otherwise choose randomly if choosen_action is None: #print("randomly choose action") # debug choosen_action = random.choice(action_list) return choosen_action
jeremiedecock/tictactoe-py
jdhp/tictactoe/player/greedy.py
Python
mit
1,951
/* * Copyright (c) 2015. Vin @ vinexs.com (MIT License) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.vinexs.view; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.widget.LinearLayout; @SuppressWarnings("unused") public class ScalableLinearLayout extends LinearLayout { private ScaleGestureDetector scaleDetector; private float scaleFactor = 1.f; private float maxScaleFactor = 1.5f; private float minScaleFactor = 0.5f; public ScalableLinearLayout(Context context) { super(context); scaleDetector = new ScaleGestureDetector(context, new ScaleListener()); } public ScalableLinearLayout(Context context, AttributeSet attrs) { super(context, attrs); scaleDetector = new ScaleGestureDetector(context, new ScaleListener()); } @SuppressLint("ClickableViewAccessibility") @Override public boolean onTouchEvent(MotionEvent event) { // Let the ScaleGestureDetector inspect all events. scaleDetector.onTouchEvent(event); return true; } @Override public void dispatchDraw(Canvas canvas) { canvas.save(); canvas.scale(scaleFactor, scaleFactor); super.dispatchDraw(canvas); canvas.restore(); } public ScalableLinearLayout setMaxScale(float scale) { maxScaleFactor = scale; return this; } public ScalableLinearLayout setMinScale(float scale) { minScaleFactor = scale; return this; } public ScaleGestureDetector getScaleGestureDetector() { return scaleDetector; } private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener { @Override public boolean onScale(ScaleGestureDetector detector) { scaleFactor *= detector.getScaleFactor(); scaleFactor = Math.max(minScaleFactor, Math.min(scaleFactor, maxScaleFactor)); invalidate(); return true; } } }
vinexs/extend-enhance-base
eeb-core/src/main/java/com/vinexs/view/ScalableLinearLayout.java
Java
mit
3,281
/* ******* TAGS ******* */ body { margin: 0; padding: 32px; font-family: Arial, Helvetica, sans-serif; font-size: 13px; color: #333333; } /* ******* COMPONENTS ******* */ /* Gridlist */ .gridlist { margin: 0; } .gridlist .control .icon { vertical-align: top; }
SerDIDG/BattlelogServersBlacklist
src/styles/options.css
CSS
mit
293
// // DRHMotorUnitData.h // TAFPlotter // // Created by Lee Walsh on 9/01/2014. // Copyright (c) 2014 Lee Walsh. All rights reserved. // #import <Foundation/Foundation.h> @interface DRHMotorUnitData : NSObject <NSCoding>{ NSNumber *unitNumber; NSNumber *unitSet; NSString *unitType; NSNumber *onsetTime; NSNumber *peakTime; NSNumber *endTime; NSNumber *inspTime; NSNumber *onsetFreq; NSNumber *peakFreq; NSNumber *endFreq; NSNumber *tonicFreq; NSNumber *normOnsetTime; NSNumber *normPeakTime; NSNumber *normEndTime; } @property NSNumber *unitNumber; @property NSNumber *unitSet; @property NSString *unitType; @property NSNumber *onsetTime; @property NSNumber *peakTime; @property NSNumber *endTime; @property NSNumber *inspTime; @property NSNumber *onsetFreq; @property NSNumber *peakFreq; @property NSNumber *endFreq; @property NSNumber *tonicFreq; @property NSNumber *normOnsetTime; @property NSNumber *normPeakTime; @property NSNumber *normEndTime; -(DRHMotorUnitData *)initWith:(NSDictionary *)unitData; +(DRHMotorUnitData *)unitWith:(NSDictionary *)unitData; -(DRHMotorUnitData *)initBlank; +(DRHMotorUnitData *)blankUnit; @end
Tanglo/TAFPLOTer
TAFPlotter/DRHMotorUnitData.h
C
mit
1,203
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("DollarTracker.Core")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DollarTracker.Core")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("4fa07611-8eb7-4660-826c-5ac7c85c07c8")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
alphaCoder/DollarTracker
DollarTracker.Net/DollarTracker.Core/Properties/AssemblyInfo.cs
C#
mit
1,412
__author__ = 'besta' class BestaPlayer: def __init__(self, fichier, player): self.fichier = fichier self.grille = self.getFirstGrid() self.best_hit = 0 self.players = player def getFirstGrid(self): """ Implements function to get the first grid. :return: the grid. """ li = [] with open(self.fichier, 'r') as fi: for line in fi.readlines(): li.append(line) return li def updateGrid(self): """ Implements function to update the grid to alter n-1 round values """ with open(self.fichier, 'r') as fi: for line in fi.readlines(): i = 0 for car in line: j = 0 if car != '\n': self.grille[i][j] = car j += 1 i += 1 def grilleEmpty(self): """ Implement function to check if the grid is empty. """ for line in self.grille: for car in line[:len(line) - 1]: if car != '0': return False return True def checkLines(self, player, inARow): """ Implements function to check the current lines setup to evaluate best combinaison. :param player: check for your numbers (your player number) or those of your opponent. :param inARow: how many tokens in a row (3 or 2). :return: true or false """ count = 0 flag = False for line_number, line in enumerate(self.grille): count = 0 for car_pos, car in enumerate(line[:len(line) - 1]): if int(car) == player and not flag: count = 1 flag = True elif int(car) == player and flag: count += 1 if count == inARow: if car_pos - inARow >= 0 and self.canPlayLine(line_number, car_pos - inARow): return True, car_pos - inARow if car_pos + 1 <= 6 and self.canPlayLine(line_number, car_pos + 1): return True, car_pos + 1 else: count = 0 return False, 0 def canPlayLine(self, line, col): """ Function to check if we can fill the line with a token. :param line: which line :param col: which column :return: true or false """ if line == 5: return self.grille[line][col] == '0' else: return self.grille[line][col] == '0' and self.grille[line + 1][col] != '0' def changeColumnInLines(self): """ Implements function to transform columns in lines to make tests eaiser. :return: a reverse matrice """ column = [] for x in xrange(7): col = '' for y in xrange(6): col += self.grille[y][x] column.append(col) return column def checkColumns(self, player, inARow): """ Implements function to check the current columns setup to evaluate best combinaison. :param player: check for your numbers (your player number) or those of your opponent. :param inARow: how many tokens in a row (3 or 2). :return: true or false """ column = self.changeColumnInLines() count = 0 flag = False for col_number, line in enumerate(column): count = 0 for car_pos, car in enumerate(line): if int(car) == player and not flag: count = 1 flag = True elif int(car) == player and flag: count += 1 if count == inARow and car_pos - inARow >= 0 and self.grille[car_pos - inARow][col_number] == '0': return True, col_number else: count = 0 return False, 0 def checkDiagonalLeftToRight(self, player, inARow): """ Implements function to check the current diagonal to evaluate best combinaison. :param player: check for your numbers or opponent ones. :param inARow: how many tokens in a row (3 or 2). :return: """ x = 3 flag = False while x < 6: count = 0 x_int = x y_int = 0 while x_int >= 0: if int(self.grille[x_int][y_int]) == player and not flag: count = 1 flag = True elif int(self.grille[x_int][y_int]) == player and flag: count += 1 if count == inARow and y_int + 1 <= 6 and x_int - 1 >= 0 and self.grille[x_int][y_int + 1] != '0': return True, y_int + 1 else: count = 0 flag = False x_int -= 1 y_int += 1 x += 1 y = 1 flag = False while y <= 3: count = 0 x_int = 5 y_int = y while y_int <= 6 and x_int >= 0: if int(self.grille[x_int][y_int]) == player and not flag: count = 1 flag = True elif int(self.grille[x_int][y_int]) == player and flag: count += 1 if count == inARow and y_int + 1 <= 6 and x_int - 1 >= 0 and self.grille[x_int][y + 1] != '0': return True, y_int + 1 else: count = 0 flage = False x_int -= 1 y_int += 1 y += 1 return False, 0 def checkDiagonalRightToLeft(self, player, inARow): """ Implements function to check the current diagonal to evaluate best combinaison. :param player: check for your numbers or opponent ones. :param inARow: how many tokens in a row (3 or 2). :return: """ x = 3 flag = False while x < 6: count = 0 x_int = x y_int = 6 while x_int >= 0: if int(self.grille[x_int][y_int]) == player and not flag: count = 1 flag = True elif int(self.grille[x_int][y_int]) == player and flag: count += 1 if count == inARow and y_int - 1 >= 0 and x_int - 1 >= 0 and self.grille[x_int][y_int - 1] != '0': return True, y_int - 1 else: count = 0 flag = False x_int -= 1 y_int -= 1 x += 1 y = 5 flag = False while y <= 3: count = 0 x_int = 5 y_int = y while y_int >= 3 and x_int >= 0: if int(self.grille[x_int][y_int]) == player and not flag: count = 1 flag = True elif int(self.grille[x_int][y_int]) == player and flag: count += 1 if count == inARow and y_int - 1 >= 0 and x_int - 1 >= 0 and self.grille[x_int][y - 1] != '0': return True, y_int - 1 else: count = 0 flage = False x_int -= 1 y_int -= 1 y -= 1 return False, 0 def checkDiagonals(self, player, inARow): """ Calls two diagonal functional. :return: an int, representing the column where to play or 0 and False if there is no pattern search. """ check = self.checkDiagonalLeftToRight(player, inARow) if check[0]: return check else: return self.checkDiagonalRightToLeft(player, inARow) def playSomeColumn(self, player, inARow): """ Call all function for a player and a number of tokens given. :param player: which player :param inARow: how many token :return: true or false (col number if true) """ methods = {'checklines': self.checkLines, 'checkcolumn': self.checkColumns, 'checkdiagonal': self.checkDiagonals} for key, function in methods.items(): which_col = function(player, inARow) if which_col[0]: return which_col return False, 0 def findFirstColumnEmpty(self): """ Implements function to get the first column where a slot remain. :return: the column """ for col in xrange(7): if self.grille[0][col] == '0': return col return -1 def decideColumn(self): """ Implements main function : to decide what is the better hit to do. :return: an int, representing the column where we play """ if self.grilleEmpty(): return 3 li_sequence = [3, 2, 1] li_players = [self.players[0], self.players[1]] for sequence in li_sequence: for player in li_players: choosen_col = self.playSomeColumn(player, sequence) if choosen_col[0]: return choosen_col[1] return self.findFirstColumnEmpty()
KeserOner/puissance4
bestaplayer.py
Python
mit
9,518
# Game Over screen. class GameOver def initialize(game) end def udpate end def draw end end
PhilCK/mermaid-game
game_over.rb
Ruby
mit
102
PP.lib.shader.shaders.color = { info: { name: 'color adjustement', author: 'Evan Wallace', link: 'https://github.com/evanw/glfx.js' }, uniforms: { textureIn: { type: "t", value: 0, texture: null }, brightness: { type: "f", value: 0.0 }, contrast: { type: "f", value: 0.0 }, hue: { type: "f", value: 0.0 }, saturation: { type: "f", value: 0.0 }, exposure: { type: "f", value: 0.0 }, negative: { type: "i", value: 0 } }, controls: { brightness: {min:-1, max: 1, step:.05}, contrast: {min:-1, max: 1, step:.05}, hue: {min:-1, max: 1, step:.05}, saturation: {min:-1, max: 1, step:.05}, exposure: {min:0, max: 1, step:.05}, negative: {} }, vertexShader: PP.lib.vextexShaderBase.join("\n"), fragmentShader: [ "varying vec2 vUv;", "uniform sampler2D textureIn;", "uniform float brightness;", "uniform float contrast;", "uniform float hue;", "uniform float saturation;", "uniform float exposure;", "uniform int negative;", "const float sqrtoftwo = 1.41421356237;", "void main() {", "vec4 color = texture2D(textureIn, vUv);", "color.rgb += brightness;", "if (contrast > 0.0) {", "color.rgb = (color.rgb - 0.5) / (1.0 - contrast) + 0.5;", "} else {", "color.rgb = (color.rgb - 0.5) * (1.0 + contrast) + 0.5;", "}", "/* hue adjustment, wolfram alpha: RotationTransform[angle, {1, 1, 1}][{x, y, z}] */", "float angle = hue * 3.14159265;", "float s = sin(angle), c = cos(angle);", "vec3 weights = (vec3(2.0 * c, -sqrt(3.0) * s - c, sqrt(3.0) * s - c) + 1.0) / 3.0;", "float len = length(color.rgb);", "color.rgb = vec3(", "dot(color.rgb, weights.xyz),", "dot(color.rgb, weights.zxy),", "dot(color.rgb, weights.yzx)", ");", "/* saturation adjustment */", "float average = (color.r + color.g + color.b) / 3.0;", "if (saturation > 0.0) {", "color.rgb += (average - color.rgb) * (1.0 - 1.0 / (1.0 - saturation));", "} else {", "color.rgb += (average - color.rgb) * (-saturation);", "}", "if(negative == 1){", " color.rgb = 1.0 - color.rgb;", "}", "if(exposure > 0.0){", " color = log2(vec4(pow(exposure + sqrtoftwo, 2.0))) * color;", "}", "gl_FragColor = color;", "}", ].join("\n") }; PP.lib.shader.shaders.bleach = { info: { name: 'Bleach', author: 'Brian Chirls @bchirls', link: 'https://github.com/brianchirls/Seriously.js' }, uniforms: { textureIn: { type: "t", value: 0, texture: null }, amount: { type: "f", value: 1.0 } }, controls: { amount: {min:0, max: 1, step:.1} }, vertexShader: PP.lib.vextexShaderBase.join("\n"), fragmentShader: [ 'varying vec2 vUv;', 'uniform sampler2D textureIn;', 'uniform float amount;', 'const vec4 one = vec4(1.0);', 'const vec4 two = vec4(2.0);', 'const vec4 lumcoeff = vec4(0.2125,0.7154,0.0721,0.0);', 'vec4 overlay(vec4 myInput, vec4 previousmix, vec4 amount) {', ' float luminance = dot(previousmix,lumcoeff);', ' float mixamount = clamp((luminance - 0.45) * 10.0, 0.0, 1.0);', ' vec4 branch1 = two * previousmix * myInput;', ' vec4 branch2 = one - (two * (one - previousmix) * (one - myInput));', ' vec4 result = mix(branch1, branch2, vec4(mixamount) );', ' return mix(previousmix, result, amount);', '}', 'void main (void) {', ' vec4 pixel = texture2D(textureIn, vUv);', ' vec4 luma = vec4(vec3(dot(pixel,lumcoeff)), pixel.a);', ' gl_FragColor = overlay(luma, pixel, vec4(amount));', '}' ].join("\n") }; PP.lib.shader.shaders.plasma = { info: { name: 'plasma', author: 'iq', link: 'http://www.iquilezles.org' }, uniforms: { resolution: { type: "v2", value: new THREE.Vector2( PP.config.dimension.width, PP.config.dimension.height )}, time: { type: "f", value: 0.0}, speed: { type: "f", value: 0.01 }, saturation: { type: "f", value: 1.0 }, waves: { type: "f", value: .2 }, wiggle: { type: "f", value: 1000.0 }, scale: { type: "f", value: 1.0 } }, controls: { speed: {min:0, max: .1, step:.001}, saturation: {min:0, max: 10, step:.01}, waves: {min:0, max: .4, step:.0001}, wiggle: {min:0, max: 10000, step:1}, scale: {min:0, max: 10, step:.01} }, update: function(e){ e.material.uniforms.time.value += e.material.uniforms.speed.value; }, vertexShader: PP.lib.vextexShaderBase.join("\n"), fragmentShader: [ "varying vec2 vUv;", "uniform float time;", "uniform float saturation;", "uniform vec2 resolution;", "uniform float waves;", "uniform float wiggle;", "uniform float scale;", "void main() {", "float x = gl_FragCoord.x*scale;", "float y = gl_FragCoord.y*scale;", "float mov0 = x+y+cos(sin(time)*2.)*100.+sin(x/100.)*wiggle;", "float mov1 = y / resolution.y / waves + time;", "float mov2 = x / resolution.x / waves;", "float r = abs(sin(mov1+time)/2.+mov2/2.-mov1-mov2+time);", "float g = abs(sin(r+sin(mov0/1000.+time)+sin(y/40.+time)+sin((x+y)/100.)*3.));", "float b = abs(sin(g+cos(mov1+mov2+g)+cos(mov2)+sin(x/1000.)));", "vec3 plasma = vec3(r,g,b) * saturation;", "gl_FragColor = vec4( plasma ,1.0);", "}" ].join("\n") }; PP.lib.shader.shaders.plasma2 = { info: { name: 'plasma2', author: 'mrDoob', link: 'http://mrdoob.com' }, uniforms: { resolution: { type: "v2", value: new THREE.Vector2( PP.config.dimension.width, PP.config.dimension.height )}, time: { type: "f", value: 0.0}, speed: { type: "f", value: 0.01 }, qteX: { type: "f", value: 80.0 }, qteY: { type: "f", value: 10.0 }, intensity: { type: "f", value: 10.0 }, hue: { type: "f", value: .25 } }, controls: { speed: {min:0, max: 1, step:.001}, qteX: {min:0, max: 200, step:1}, qteY: {min:0, max: 200, step:1}, intensity: {min:0, max: 50, step:.1}, hue: {min:0, max: 2, step:.001} }, update: function(e){ e.material.uniforms.time.value += e.material.uniforms.speed.value; }, vertexShader: PP.lib.vextexShaderBase.join("\n"), fragmentShader: [ "uniform float time;", "uniform vec2 resolution;", "uniform float qteX;", "uniform float qteY;", "uniform float intensity;", "uniform float hue;", "void main() {", "vec2 position = gl_FragCoord.xy / resolution.xy;", "float color = 0.0;", "color += sin( position.x * cos( time / 15.0 ) * qteX ) + cos( position.y * cos( time / 15.0 ) * qteY );", "color += sin( position.y * sin( time / 10.0 ) * 40.0 ) + cos( position.x * sin( time / 25.0 ) * 40.0 );", "color += sin( position.x * sin( time / 5.0 ) * 10.0 ) + sin( position.y * sin( time / 35.0 ) * 80.0 );", "color *= sin( time / intensity ) * 0.5;", "gl_FragColor = vec4( vec3( color, color * (hue*2.0), sin( color + time / (hue*12.0) ) * (hue*3.0) ), 1.0 );", "}" ].join("\n") }; PP.lib.shader.shaders.plasma3 = { info: { name: 'plasma 3', author: 'Hakim El Hattab', link: 'http://hakim.se' }, uniforms: { color: { type: "c", value: new THREE.Color( 0x8CC6DA ) }, resolution: { type: "v2", value: new THREE.Vector2( PP.config.dimension.width, PP.config.dimension.height )}, time: { type: "f", value: 0.0}, speed: { type: "f", value: 0.05 }, scale: { type: "f", value: 10.0 }, quantity: { type: "f", value: 5.0 }, lens: { type: "f", value: 2.0 }, intensity: { type: "f", value: .5 } }, controls: { speed: {min:0, max: 1, step:.001}, scale: {min:0, max: 100, step:.1}, quantity: {min:0, max: 100, step:1}, lens: {min:0, max: 100, step:1}, intensity: {min:0, max: 5, step:.01} }, update: function(e){ e.material.uniforms.time.value += e.material.uniforms.speed.value; }, vertexShader: PP.lib.vextexShaderBase.join("\n"), fragmentShader: [ "uniform float time;", "uniform vec2 resolution;", "uniform vec3 color;", "uniform float scale;", "uniform float quantity;", "uniform float lens;", "uniform float intensity;", "void main() {", "vec2 p = -1.0 + 2.0 * gl_FragCoord.xy / resolution.xy;", "p = p * scale;", "vec2 uv;", "float a = atan(p.y,p.x);", "float r = sqrt(dot(p,p));", "uv.x = 2.0*a/3.1416;", "uv.y = -time+ sin(7.0*r+time) + .7*cos(time+7.0*a);", "float w = intensity+1.0*(sin(time+lens*r)+ 1.0*cos(time+(quantity * 2.0)*a));", "gl_FragColor = vec4(color*w,1.0);", "}" ].join("\n") }; PP.lib.shader.shaders.plasma4 = { info: { name: 'plasma 4 (vortex)', author: 'Hakim El Hattab', link: 'http://hakim.se' }, uniforms: { color: { type: "c", value: new THREE.Color( 0xff5200 ) }, // 0x8CC6DA resolution: { type: "v2", value: new THREE.Vector2( PP.config.dimension.width, PP.config.dimension.height )}, time: { type: "f", value: 0.0}, speed: { type: "f", value: 0.05 }, scale: { type: "f", value: 20.0 }, wobble: { type: "f", value: 1.0 }, ripple: { type: "f", value: 5.0 }, light: { type: "f", value: 2.0 } }, controls: { speed: {min:0, max: 1, step:.001}, scale: {min:0, max: 100, step:.1}, wobble: {min:0, max: 50, step:1}, ripple: {min:0, max: 50, step:.1}, light: {min:1, max: 50, step:1} }, update: function(e){ e.material.uniforms.time.value += e.material.uniforms.speed.value; }, vertexShader: PP.lib.vextexShaderBase.join("\n"), fragmentShader: [ "uniform float time;", "uniform vec2 resolution;", "uniform vec3 color;", "uniform float scale;", "uniform float wobble;", "uniform float ripple;", "uniform float light;", "void main() {", "vec2 p = -1.0 + 2.0 * gl_FragCoord.xy / resolution.xy;", "vec2 uv;", "float a = atan(p.y,p.x);", "float r = sqrt(dot(p,p));", "float u = cos(a*(wobble * 2.0) + ripple * sin(-time + scale * r));", "float intensity = sqrt(pow(abs(p.x),light) + pow(abs(p.y),light));", "vec3 result = u*intensity*color;", "gl_FragColor = vec4(result,1.0);", "}" ].join("\n") }; PP.lib.shader.shaders.plasma5 = { info: { name: 'plasma 5', author: 'Silexars', link: 'http://www.silexars.com' }, uniforms: { resolution: { type: "v2", value: new THREE.Vector2( PP.config.dimension.width, PP.config.dimension.height )}, time: { type: "f", value: 0.0}, speed: { type: "f", value: 0.01 } }, controls: { speed: {min:0, max: .2, step:.001} }, update: function(e){ e.material.uniforms.time.value += e.material.uniforms.speed.value; }, vertexShader: PP.lib.vextexShaderBase.join("\n"), fragmentShader: [ "uniform vec2 resolution;", "uniform float time;", "void main() {", "vec3 col;", "float l,z=time;", "for(int i=0;i<3;i++){", "vec2 uv;", "vec2 p=gl_FragCoord.xy/resolution.xy;", "uv=p;", "p-=.5;", "p.x*=resolution.x/resolution.y;", "z+=.07;", "l=length(p);", "uv+=p/l*(sin(z)+1.)*abs(sin(l*9.-z*2.));", "col[i]=.01/length(abs(mod(uv,1.)-.5));", "}", "gl_FragColor=vec4(col/l,1.0);", "}" ].join("\n") }; PP.lib.shader.shaders.plasmaByTexture = { info: { name: 'plasma by texture', author: 'J3D', link: 'http://www.everyday3d.com/j3d/demo/011_Plasma.html' }, uniforms: { textureIn: { type: "t", value: 0, texture: null }, time: { type: "f", value: 0.0}, speed: { type: "f", value: 0.01 } }, controls: { speed: {min:0, max: .1, step:.001} }, update: function(e){ e.material.uniforms.time.value += e.material.uniforms.speed.value; }, vertexShader: PP.lib.vextexShaderBase.join("\n"), fragmentShader: [ "varying vec2 vUv;", "uniform sampler2D textureIn;", "uniform float time;", "void main() {", "vec2 ca = vec2(0.1, 0.2);", "vec2 cb = vec2(0.7, 0.9);", "float da = distance(vUv, ca);", "float db = distance(vUv, cb);", "float t = time * 0.5;", "float c1 = sin(da * cos(t) * 16.0 + t * 4.0);", "float c2 = cos(vUv.y * 8.0 + t);", "float c3 = cos(db * 14.0) + sin(t);", "float p = (c1 + c2 + c3) / 3.0;", "gl_FragColor = texture2D(textureIn, vec2(p, p));", "}" ].join("\n") };
rdad/PP.js
src/lib/Shader.color.js
JavaScript
mit
20,938
/* Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'save', 'de-ch', { toolbar: 'Speichern' } );
waxe/waxe.xml
waxe/xml/static/ckeditor/plugins/save/lang/de-ch.js
JavaScript
mit
225
// // The MIT License(MIT) // // Copyright(c) 2014 Demonsaw LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include "command/socket_command.h" #include "component/socket_component.h" #include "component/tunnel_component.h" #include "entity/entity.h" #include "http/http_socket.h" #include "message/request/request_message.h" #include "message/response/response_message.h" namespace eja { // Client socket_request_message::ptr client_socket_command::execute(const entity::ptr router) { return socket_request_message::create(); } void client_socket_command::execute(const entity::ptr router, const std::shared_ptr<socket_response_message> response) { // N/A } // Router socket_response_message::ptr router_socket_command::execute(const entity::ptr client, const http_socket::ptr socket, const socket_request_message::ptr request) { // Socket const auto socket_set = m_entity->get<socket_set_component>(); { thread_lock(socket_set); socket_set->erase(socket); } // Tunnel const auto tunnel_list = client->get<tunnel_list_component>(); { thread_lock(tunnel_list); tunnel_list->push_back(socket); } return socket_response_message::create(); } }
demonsaw/Code
ds3/3_core/command/socket_command.cpp
C++
mit
2,225
cookbook_path ["berks-cookbooks", "cookbooks", "site-cookbooks"] node_path "nodes" role_path "roles" environment_path "environments" data_bag_path "data_bags" #encrypted_data_bag_secret "data_bag_key" knife[:berkshelf_path] = "berks-cookbooks" Chef::Config[:ssl_verify_mode] = :verify_peer if defined? ::Chef
rudijs/devops-starter
app/kitchen/.chef/knife.rb
Ruby
mit
330
// Specifically test buffer module regression. import { Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer, transcode, TranscodeEncoding, constants, kMaxLength, kStringMaxLength, Blob, } from 'buffer'; const utf8Buffer = new Buffer('test'); const base64Buffer = new Buffer('', 'base64'); const octets: Uint8Array = new Uint8Array(123); const octetBuffer = new Buffer(octets); const sharedBuffer = new Buffer(octets.buffer); const copiedBuffer = new Buffer(utf8Buffer); console.log(Buffer.isBuffer(octetBuffer)); console.log(Buffer.isEncoding('utf8')); console.log(Buffer.byteLength('xyz123')); console.log(Buffer.byteLength('xyz123', 'ascii')); const result1 = Buffer.concat([utf8Buffer, base64Buffer] as ReadonlyArray<Uint8Array>); const result2 = Buffer.concat([utf8Buffer, base64Buffer] as ReadonlyArray<Uint8Array>, 9999999); // Module constants { const value1: number = constants.MAX_LENGTH; const value2: number = constants.MAX_STRING_LENGTH; const value3: number = kMaxLength; const value4: number = kStringMaxLength; } // Class Methods: Buffer.swap16(), Buffer.swa32(), Buffer.swap64() { const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); buf.swap16(); buf.swap32(); buf.swap64(); } // Class Method: Buffer.from(data) { // Array const buf1: Buffer = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72] as ReadonlyArray<number>); // Buffer const buf2: Buffer = Buffer.from(buf1, 1, 2); // String const buf3: Buffer = Buffer.from('this is a tést'); // ArrayBuffer const arrUint16: Uint16Array = new Uint16Array(2); arrUint16[0] = 5000; arrUint16[1] = 4000; const buf4: Buffer = Buffer.from(arrUint16.buffer); const arrUint8: Uint8Array = new Uint8Array(2); const buf5: Buffer = Buffer.from(arrUint8); const buf6: Buffer = Buffer.from(buf1); const sb: SharedArrayBuffer = {} as any; const buf7: Buffer = Buffer.from(sb); // $ExpectError Buffer.from({}); } // Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) { const arr: Uint16Array = new Uint16Array(2); arr[0] = 5000; arr[1] = 4000; let buf: Buffer; buf = Buffer.from(arr.buffer, 1); buf = Buffer.from(arr.buffer, 0, 1); // $ExpectError Buffer.from("this is a test", 1, 1); // Ideally passing a normal Buffer would be a type error too, but it's not // since Buffer is assignable to ArrayBuffer currently } // Class Method: Buffer.from(str[, encoding]) { const buf2: Buffer = Buffer.from('7468697320697320612074c3a97374', 'hex'); /* tslint:disable-next-line no-construct */ Buffer.from(new String("DEADBEEF"), "hex"); // $ExpectError Buffer.from(buf2, 'hex'); } // Class Method: Buffer.from(object, [, byteOffset[, length]]) (Implicit coercion) { const pseudoBuf = { valueOf() { return Buffer.from([1, 2, 3]); } }; let buf: Buffer = Buffer.from(pseudoBuf); const pseudoString = { valueOf() { return "Hello"; }}; buf = Buffer.from(pseudoString); buf = Buffer.from(pseudoString, "utf-8"); // $ExpectError Buffer.from(pseudoString, 1, 2); const pseudoArrayBuf = { valueOf() { return new Uint16Array(2); } }; buf = Buffer.from(pseudoArrayBuf, 1, 1); } // Class Method: Buffer.alloc(size[, fill[, encoding]]) { const buf1: Buffer = Buffer.alloc(5); const buf2: Buffer = Buffer.alloc(5, 'a'); const buf3: Buffer = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); } // Class Method: Buffer.allocUnsafe(size) { const buf: Buffer = Buffer.allocUnsafe(5); } // Class Method: Buffer.allocUnsafeSlow(size) { const buf: Buffer = Buffer.allocUnsafeSlow(10); } // Class Method byteLenght { let len: number; len = Buffer.byteLength("foo"); len = Buffer.byteLength("foo", "utf8"); const b = Buffer.from("bar"); len = Buffer.byteLength(b); len = Buffer.byteLength(b, "utf16le"); const ab = new ArrayBuffer(15); len = Buffer.byteLength(ab); len = Buffer.byteLength(ab, "ascii"); const dv = new DataView(ab); len = Buffer.byteLength(dv); len = Buffer.byteLength(dv, "utf16le"); } // Class Method poolSize { let s: number; s = Buffer.poolSize; Buffer.poolSize = 4096; } // Test that TS 1.6 works with the 'as Buffer' annotation // on isBuffer. let a: Buffer | number; a = new Buffer(10); if (Buffer.isBuffer(a)) { a.writeUInt8(3, 4); } // write* methods return offsets. const b = new Buffer(16); let result: number = b.writeUInt32LE(0, 0); result = b.writeUInt16LE(0, 4); result = b.writeUInt8(0, 6); result = b.writeInt8(0, 7); result = b.writeDoubleLE(0, 8); result = b.write('asd'); result = b.write('asd', 'hex'); result = b.write('asd', 123, 'hex'); result = b.write('asd', 123, 123, 'hex'); // fill returns the input buffer. b.fill('a').fill('b'); { const buffer = new Buffer('123'); let index: number; index = buffer.indexOf("23"); index = buffer.indexOf("23", 1); index = buffer.indexOf("23", 1, "utf8"); index = buffer.indexOf(23); index = buffer.indexOf(buffer); } { const buffer = new Buffer('123'); let index: number; index = buffer.lastIndexOf("23"); index = buffer.lastIndexOf("23", 1); index = buffer.lastIndexOf("23", 1, "utf8"); index = buffer.lastIndexOf(23); index = buffer.lastIndexOf(buffer); } { const buffer = new Buffer('123'); const val: [number, number] = [1, 1]; /* comment out for --target es5 for (let entry of buffer.entries()) { val = entry; } */ } { const buffer = new Buffer('123'); let includes: boolean; includes = buffer.includes("23"); includes = buffer.includes("23", 1); includes = buffer.includes("23", 1, "utf8"); includes = buffer.includes(23); includes = buffer.includes(23, 1); includes = buffer.includes(23, 1, "utf8"); includes = buffer.includes(buffer); includes = buffer.includes(buffer, 1); includes = buffer.includes(buffer, 1, "utf8"); } { const buffer = new Buffer('123'); const val = 1; /* comment out for --target es5 for (let key of buffer.keys()) { val = key; } */ } { const buffer = new Buffer('123'); const val = 1; /* comment out for --target es5 for (let value of buffer.values()) { val = value; } */ } // Imported Buffer from buffer module works properly { const b = new ImportedBuffer('123'); b.writeUInt8(0, 6); const sb = new ImportedSlowBuffer(43); b.writeUInt8(0, 6); } // Buffer has Uint8Array's buffer field (an ArrayBuffer). { const buffer = new Buffer('123'); const octets = new Uint8Array(buffer.buffer); } // Inherited from Uint8Array but return buffer { const b = Buffer.from('asd'); let res: Buffer = b.reverse(); res = b.subarray(); res = b.subarray(1); res = b.subarray(1, 2); } // Buffer module, transcode function { transcode(Buffer.from('€'), 'utf8', 'ascii'); // $ExpectType Buffer const source: TranscodeEncoding = 'utf8'; const target: TranscodeEncoding = 'ascii'; transcode(Buffer.from('€'), source, target); // $ExpectType Buffer } { const a = Buffer.alloc(1000); a.writeBigInt64BE(123n); a.writeBigInt64LE(123n); a.writeBigUInt64BE(123n); a.writeBigUInt64LE(123n); let b: bigint = a.readBigInt64BE(123); b = a.readBigInt64LE(123); b = a.readBigUInt64LE(123); b = a.readBigUInt64BE(123); } async () => { const blob = new Blob(['asd', Buffer.from('test'), new Blob(['dummy'])], { type: 'application/javascript', encoding: 'base64', }); blob.size; // $ExpectType number blob.type; // $ExpectType string blob.arrayBuffer(); // $ExpectType Promise<ArrayBuffer> blob.text(); // $ExpectType Promise<string> blob.slice(); // $ExpectType Blob blob.slice(1); // $ExpectType Blob blob.slice(1, 2); // $ExpectType Blob blob.slice(1, 2, 'other'); // $ExpectType Blob };
georgemarshall/DefinitelyTyped
types/node/test/buffer.ts
TypeScript
mit
8,030
/* * Copyright (c) 2016-2017 Mozilla Foundation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ package nu.validator.xml; import java.io.IOException; import java.util.Arrays; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.DTDHandler; import org.xml.sax.EntityResolver; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.XMLReader; public final class UseCountingXMLReaderWrapper implements XMLReader, ContentHandler { private final XMLReader wrappedReader; private ContentHandler contentHandler; private ErrorHandler errorHandler; private HttpServletRequest request; private StringBuilder documentContent; private boolean inBody; private boolean loggedLinkWithCharset; private boolean loggedScriptWithCharset; private boolean loggedStyleInBody; private boolean loggedRelAlternate; private boolean loggedRelAuthor; private boolean loggedRelBookmark; private boolean loggedRelCanonical; private boolean loggedRelDnsPrefetch; private boolean loggedRelExternal; private boolean loggedRelHelp; private boolean loggedRelIcon; private boolean loggedRelLicense; private boolean loggedRelNext; private boolean loggedRelNofollow; private boolean loggedRelNoopener; private boolean loggedRelNoreferrer; private boolean loggedRelPingback; private boolean loggedRelPreconnect; private boolean loggedRelPrefetch; private boolean loggedRelPreload; private boolean loggedRelPrerender; private boolean loggedRelPrev; private boolean loggedRelSearch; private boolean loggedRelServiceworker; private boolean loggedRelStylesheet; private boolean loggedRelTag; public UseCountingXMLReaderWrapper(XMLReader wrappedReader, HttpServletRequest request) { this.wrappedReader = wrappedReader; this.contentHandler = wrappedReader.getContentHandler(); this.request = request; this.inBody = false; this.loggedLinkWithCharset = false; this.loggedScriptWithCharset = false; this.loggedStyleInBody = false; this.loggedRelAlternate = false; this.loggedRelAuthor = false; this.loggedRelBookmark = false; this.loggedRelCanonical = false; this.loggedRelAlternate = false; this.loggedRelAuthor = false; this.loggedRelBookmark = false; this.loggedRelCanonical = false; this.loggedRelDnsPrefetch = false; this.loggedRelExternal = false; this.loggedRelHelp = false; this.loggedRelIcon = false; this.loggedRelLicense = false; this.loggedRelNext = false; this.loggedRelNofollow = false; this.loggedRelNoopener = false; this.loggedRelNoreferrer = false; this.loggedRelPingback = false; this.loggedRelPreconnect = false; this.loggedRelPrefetch = false; this.loggedRelPreload = false; this.loggedRelPrerender = false; this.loggedRelPrev = false; this.loggedRelSearch = false; this.loggedRelServiceworker = false; this.loggedRelStylesheet = false; this.loggedRelTag = false; this.documentContent = new StringBuilder(); wrappedReader.setContentHandler(this); } /** * @see org.xml.sax.helpers.XMLFilterImpl#characters(char[], int, int) */ @Override public void characters(char[] ch, int start, int length) throws SAXException { if (contentHandler == null) { return; } contentHandler.characters(ch, start, length); } /** * @see org.xml.sax.helpers.XMLFilterImpl#endElement(java.lang.String, * java.lang.String, java.lang.String) */ @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (contentHandler == null) { return; } contentHandler.endElement(uri, localName, qName); } /** * @see org.xml.sax.helpers.XMLFilterImpl#startDocument() */ @Override public void startDocument() throws SAXException { if (contentHandler == null) { return; } documentContent.setLength(0); contentHandler.startDocument(); } /** * @see org.xml.sax.helpers.XMLFilterImpl#startElement(java.lang.String, * java.lang.String, java.lang.String, org.xml.sax.Attributes) */ @Override public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { if (contentHandler == null) { return; } if ("link".equals(localName)) { boolean hasAppleTouchIcon = false; boolean hasSizes = false; for (int i = 0; i < atts.getLength(); i++) { if ("rel".equals(atts.getLocalName(i))) { if (atts.getValue(i).contains("apple-touch-icon")) { hasAppleTouchIcon = true; } } else if ("sizes".equals(atts.getLocalName(i))) { hasSizes = true; } else if ("charset".equals(atts.getLocalName(i)) && !loggedLinkWithCharset) { loggedLinkWithCharset = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/link-with-charset-found", true); } } } if (request != null && hasAppleTouchIcon && hasSizes) { request.setAttribute( "http://validator.nu/properties/apple-touch-icon-with-sizes-found", true); } } else if ("script".equals(localName) && !loggedScriptWithCharset) { for (int i = 0; i < atts.getLength(); i++) { if ("charset".equals(atts.getLocalName(i))) { loggedScriptWithCharset = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/script-with-charset-found", true); } } } } else if (inBody && "style".equals(localName) && !loggedStyleInBody) { loggedStyleInBody = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/style-in-body-found", true); } } if (atts.getIndex("", "rel") > -1 && ("link".equals(localName) || "a".equals(localName))) { List<String> relValues = Arrays.asList( atts.getValue("", "rel").trim().toLowerCase() // .split("\\s+")); if (relValues.contains("alternate") && !loggedRelAlternate) { loggedRelAlternate = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-alternate-found", true); } } if (relValues.contains("author") && !loggedRelAuthor) { loggedRelAuthor = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-author-found", true); } } if (relValues.contains("bookmark") && !loggedRelBookmark) { loggedRelBookmark = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-bookmark-found", true); } } if (relValues.contains("canonical") && !loggedRelCanonical) { loggedRelCanonical = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-canonical-found", true); } } if (relValues.contains("dns-prefetch") && !loggedRelDnsPrefetch) { loggedRelDnsPrefetch = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-dns-prefetch-found", true); } } if (relValues.contains("external") && !loggedRelExternal) { loggedRelExternal = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-external-found", true); } } if (relValues.contains("help") && !loggedRelHelp) { loggedRelHelp = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-help-found", true); } } if (relValues.contains("icon") && !loggedRelIcon) { loggedRelIcon = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-icon-found", true); } } if (relValues.contains("license") && !loggedRelLicense) { loggedRelLicense = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-license-found", true); } } if (relValues.contains("next") && !loggedRelNext) { loggedRelNext = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-next-found", true); } } if (relValues.contains("nofollow") && !loggedRelNofollow) { loggedRelNofollow = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-nofollow-found", true); } } if (relValues.contains("noopener") && !loggedRelNoopener) { loggedRelNoopener = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-noopener-found", true); } } if (relValues.contains("noreferrer") && !loggedRelNoreferrer) { loggedRelNoreferrer = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-noreferrer-found", true); } } if (relValues.contains("pingback") && !loggedRelPingback) { loggedRelPingback = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-pingback-found", true); } } if (relValues.contains("preconnect") && !loggedRelPreconnect) { loggedRelPreconnect = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-preconnect-found", true); } } if (relValues.contains("prefetch") && !loggedRelPrefetch) { loggedRelPrefetch = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-prefetch-found", true); } } if (relValues.contains("preload") && !loggedRelPreload) { loggedRelPreload = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-preload-found", true); } } if (relValues.contains("prerender") && !loggedRelPrerender) { loggedRelPrerender = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-prerender-found", true); } } if (relValues.contains("prev") && !loggedRelPrev) { loggedRelPrev = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-prev-found", true); } } if (relValues.contains("search") && !loggedRelSearch) { loggedRelSearch = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-search-found", true); } } if (relValues.contains("serviceworker") && !loggedRelServiceworker) { loggedRelServiceworker = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-serviceworker-found", true); } } if (relValues.contains("stylesheet") && !loggedRelStylesheet) { loggedRelStylesheet = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-stylesheet-found", true); } } if (relValues.contains("tag") && !loggedRelTag) { loggedRelTag = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-tag-found", true); } } } contentHandler.startElement(uri, localName, qName, atts); } /** * @see org.xml.sax.helpers.XMLFilterImpl#setDocumentLocator(org.xml.sax.Locator) */ @Override public void setDocumentLocator(Locator locator) { if (contentHandler == null) { return; } contentHandler.setDocumentLocator(locator); } @Override public ContentHandler getContentHandler() { return contentHandler; } /** * @throws SAXException * @see org.xml.sax.ContentHandler#endDocument() */ @Override public void endDocument() throws SAXException { if (contentHandler == null) { return; } contentHandler.endDocument(); } /** * @param prefix * @throws SAXException * @see org.xml.sax.ContentHandler#endPrefixMapping(java.lang.String) */ @Override public void endPrefixMapping(String prefix) throws SAXException { if (contentHandler == null) { return; } contentHandler.endPrefixMapping(prefix); } /** * @param ch * @param start * @param length * @throws SAXException * @see org.xml.sax.ContentHandler#ignorableWhitespace(char[], int, int) */ @Override public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { if (contentHandler == null) { return; } contentHandler.ignorableWhitespace(ch, start, length); } /** * @param target * @param data * @throws SAXException * @see org.xml.sax.ContentHandler#processingInstruction(java.lang.String, * java.lang.String) */ @Override public void processingInstruction(String target, String data) throws SAXException { if (contentHandler == null) { return; } contentHandler.processingInstruction(target, data); } /** * @param name * @throws SAXException * @see org.xml.sax.ContentHandler#skippedEntity(java.lang.String) */ @Override public void skippedEntity(String name) throws SAXException { if (contentHandler == null) { return; } contentHandler.skippedEntity(name); } /** * @param prefix * @param uri * @throws SAXException * @see org.xml.sax.ContentHandler#startPrefixMapping(java.lang.String, * java.lang.String) */ @Override public void startPrefixMapping(String prefix, String uri) throws SAXException { if (contentHandler == null) { return; } contentHandler.startPrefixMapping(prefix, uri); } /** * @return * @see org.xml.sax.XMLReader#getDTDHandler() */ @Override public DTDHandler getDTDHandler() { return wrappedReader.getDTDHandler(); } /** * @return * @see org.xml.sax.XMLReader#getEntityResolver() */ @Override public EntityResolver getEntityResolver() { return wrappedReader.getEntityResolver(); } /** * @return * @see org.xml.sax.XMLReader#getErrorHandler() */ @Override public ErrorHandler getErrorHandler() { return errorHandler; } /** * @param name * @return * @throws SAXNotRecognizedException * @throws SAXNotSupportedException * @see org.xml.sax.XMLReader#getFeature(java.lang.String) */ @Override public boolean getFeature(String name) throws SAXNotRecognizedException, SAXNotSupportedException { return wrappedReader.getFeature(name); } /** * @param name * @return * @throws SAXNotRecognizedException * @throws SAXNotSupportedException * @see org.xml.sax.XMLReader#getProperty(java.lang.String) */ @Override public Object getProperty(String name) throws SAXNotRecognizedException, SAXNotSupportedException { return wrappedReader.getProperty(name); } /** * @param input * @throws IOException * @throws SAXException * @see org.xml.sax.XMLReader#parse(org.xml.sax.InputSource) */ @Override public void parse(InputSource input) throws IOException, SAXException { wrappedReader.parse(input); } /** * @param systemId * @throws IOException * @throws SAXException * @see org.xml.sax.XMLReader#parse(java.lang.String) */ @Override public void parse(String systemId) throws IOException, SAXException { wrappedReader.parse(systemId); } /** * @param handler * @see org.xml.sax.XMLReader#setContentHandler(org.xml.sax.ContentHandler) */ @Override public void setContentHandler(ContentHandler handler) { contentHandler = handler; } /** * @param handler * @see org.xml.sax.XMLReader#setDTDHandler(org.xml.sax.DTDHandler) */ @Override public void setDTDHandler(DTDHandler handler) { wrappedReader.setDTDHandler(handler); } /** * @param resolver * @see org.xml.sax.XMLReader#setEntityResolver(org.xml.sax.EntityResolver) */ @Override public void setEntityResolver(EntityResolver resolver) { wrappedReader.setEntityResolver(resolver); } /** * @param handler * @see org.xml.sax.XMLReader#setErrorHandler(org.xml.sax.ErrorHandler) */ @Override public void setErrorHandler(ErrorHandler handler) { wrappedReader.setErrorHandler(handler); } /** * @param name * @param value * @throws SAXNotRecognizedException * @throws SAXNotSupportedException * @see org.xml.sax.XMLReader#setFeature(java.lang.String, boolean) */ @Override public void setFeature(String name, boolean value) throws SAXNotRecognizedException, SAXNotSupportedException { wrappedReader.setFeature(name, value); } /** * @param name * @param value * @throws SAXNotRecognizedException * @throws SAXNotSupportedException * @see org.xml.sax.XMLReader#setProperty(java.lang.String, * java.lang.Object) */ @Override public void setProperty(String name, Object value) throws SAXNotRecognizedException, SAXNotSupportedException { wrappedReader.setProperty(name, value); } }
tripu/validator
src/nu/validator/xml/UseCountingXMLReaderWrapper.java
Java
mit
22,613
"use strict"; var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _ = require("../../../"); var _2 = _interopRequireDefault(_); describe(".toString()", function () { var User = (function (_Model) { _inherits(User, _Model); function User() { _classCallCheck(this, User); _get(Object.getPrototypeOf(User.prototype), "constructor", this).apply(this, arguments); } return User; })(_2["default"]); describe("User.find.one.where(\"id\", 1)", function () { it("should return a string representation of the chain", function () { User.find.one.where("id", 1).toString().should.eql("User.find.one.where(\"id\", 1)"); }); it("should not matter which order the chain is called in", function () { User.find.where("id", 1).one.toString().should.eql("User.find.one.where(\"id\", 1)"); }); }); describe("User.find.all.where(\"id\", 1)", function () { it("should return a string representation of the chain", function () { User.find.all.where("id", 1).toString().should.eql("User.find.all.where(\"id\", 1)"); }); }); describe("User.find.where(\"id\", \"<\", 10).andWhere(\"id\", \">\", 1)", function () { it("should return a string representation of the chain", function () { User.find.where("id", "<", 10).andWhere("id", ">", 1).toString().should.eql("User.find.where(\"id\", \"<\", 10).andWhere(\"id\", \">\", 1)"); }); }); describe("User.find.where(\"id\", \"<\", 10).andWhere(\"id\", \">\", 1).andWhere(\"id\", \"!=\", 3)", function () { it("should return a string representation of the chain", function () { User.find.where("id", "<", 10).andWhere("id", ">", 1).andWhere("id", "!=", 3).toString().should.eql("User.find.where(\"id\", \"<\", 10).andWhere(\"id\", \">\", 1).andWhere(\"id\", \"!=\", 3)"); }); }); describe("User.find.where(\"id\", \"<\", 10).orWhere(\"id\", \">\", 1)", function () { it("should return a string representation of the chain", function () { User.find.where("id", "<", 10).orWhere("id", ">", 1).toString().should.eql("User.find.where(\"id\", \"<\", 10).orWhere(\"id\", \">\", 1)"); }); }); describe("User.find.where(\"id\", \"<\", 10).groupBy(\"categoryId\")", function () { it("should return a string representation of the chain", function () { User.find.where("id", "<", 10).groupBy("categoryId").toString().should.eql("User.find.where(\"id\", \"<\", 10).groupBy(\"categoryId\")"); }); }); describe("User.find.where(\"id\", \"<\", 10).orderBy(\"categoryId\")", function () { it("should return a string representation of the chain", function () { User.find.where("id", "<", 10).orderBy("categoryId", "desc").toString().should.eql("User.find.where(\"id\", \"<\", 10).orderBy(\"categoryId\", \"desc\")"); }); }); describe("User.find.where(\"id\", \">\", 2).limit(4)", function () { it("should return a string representation of the chain", function () { User.find.where("id", ">", 2).limit(4).toString().should.eql("User.find.where(\"id\", \">\", 2).limit(4)"); }); }); describe("User.count.where(\"id\", 1)", function () { it("should return a string representation of the chain", function () { User.count.where("id", 1).toString().should.eql("User.count.where(\"id\", 1)"); }); }); });
FreeAllMedia/dovima
es5/spec/model/toString.spec.js
JavaScript
mit
4,683
namespace FTJFundChoice.OrionClient.Models.Enums { public enum HowIsAdvRegistered { Unknown = 0, SECRegistered = 1, StateRegistered = 2, Unregistered = 3, Other = 4 } }
FTJFundChoice/OrionClient
FTJFundChoice.OrionClient/Models/Enums/HowIsAdvRegistered.cs
C#
mit
220
<?php //Announce.php namespace litepubl\post; use litepubl\view\Lang; use litepubl\view\Schema; use litepubl\view\Vars; /** * Post announces * * @property-write callable $before * @property-write callable $after * @property-write callable $onHead * @method array before(array $params) * @method array after(array $params) * @method array onHead(array $params) */ class Announce extends \litepubl\core\Events { use \litepubl\core\PoolStorageTrait; protected function create() { parent::create(); $this->basename = 'announce'; $this->addEvents('before', 'after', 'onhead'); } public function getHead(array $items): string { $result = ''; if (count($items)) { Posts::i()->loadItems($items); foreach ($items as $id) { $post = Post::i($id); $result.= $post->rawhead; } } $r = $this->onHead(['content' => $result, 'items' => $items]); return $r['content']; } public function getPosts(array $items, Schema $schema): string { $r = $this->before(['content' => '', 'items' => $items, 'schema' => $schema]); $result = $r['content']; $theme = $schema->theme; $items = $r['items']; if (count($items)) { Posts::i()->loadItems($items); $vars = new Vars(); $vars->lang = Lang::i('default'); foreach ($items as $id) { $post = Post::i($id); $view = $post->view; $vars->post = $view; $view->setTheme($theme); $result.= $view->getAnnounce($schema->postannounce); // has $author.* tags in tml if (isset($vars->author)) { unset($vars->author); } } } if ($tmlContainer = $theme->templates['content.excerpts' . ($schema->postannounce == 'excerpt' ? '' : '.' . $schema->postannounce) ]) { $result = str_replace('$excerpt', $result, $theme->parse($tmlContainer)); } $r = $this->after(['content' => $result, 'items' => $items, 'schema' => $schema]); return $r['content']; } public function getNavi(array $items, Schema $schema, string $url, int $count): string { $result = $this->getPosts($items, $schema); $result .= $this->getPages($schema, $url, $count); return $result; } public function getPages(Schema $schema, string $url, int $count): string { $app = $this->getApp(); if ($schema->perpage) { $perpage = $schema->perpage; } else { $perpage = $app->options->perpage; } return $schema->theme->getPages($url, $app->context->request->page, ceil($count / $perpage)); } //used in plugins such as singlecat public function getLinks(string $where, string $tml): string { $db = $this->getApp()->db; $t = $db->posts; $items = $db->res2assoc( $db->query( "select $t.id, $t.title, $db->urlmap.url as url from $t, $db->urlmap where $t.status = 'published' and $where and $db->urlmap.id = $t.idurl" ) ); if (!count($items)) { return ''; } $result = ''; $args = new Args(); $theme = Theme::i(); foreach ($items as $item) { $args->add($item); $result.= $theme->parseArg($tml, $args); } return $result; } } //Factory.php namespace litepubl\post; use litepubl\comments\Comments; use litepubl\comments\Pingbacks; use litepubl\core\Users; use litepubl\pages\Users as UserPages; use litepubl\tag\Cats; use litepubl\tag\Tags; class Factory { use \litepubl\core\Singleton; public function __get($name) { return $this->{'get' . $name}(); } public function getPosts() { return Posts::i(); } public function getFiles() { return Files::i(); } public function getFileView() { return FileView::i(); } public function getTags() { return Tags::i(); } public function getCats() { return Cats::i(); } public function getCategories() { return $this->getcats(); } public function getTemplatecomments() { return Templates::i(); } public function getComments($id) { return Comments::i($id); } public function getPingbacks($id) { return Pingbacks::i($id); } public function getMeta($id) { return Meta::i($id); } public function getUsers() { return Users::i(); } public function getUserpages() { return UserPages::i(); } public function getView() { return View::i(); } } //Files.php namespace litepubl\post; use litepubl\core\Event; use litepubl\core\Str; use litepubl\view\Filter; /** * Manage uploaded files * * @property-read FilesItems $itemsPosts * @property-write callable $changed * @property-write callable $edited * @method array changed(array $params) * @method array edited(array $params) */ class Files extends \litepubl\core\Items { protected function create() { $this->dbversion = true; parent::create(); $this->basename = 'files'; $this->table = 'files'; $this->addEvents('changed', 'edited'); } public function getItemsPosts(): FilesItems { return FilesItems::i(); } public function preload(array $items) { $items = array_diff($items, array_keys($this->items)); if (count($items)) { $this->select(sprintf('(id in (%1$s)) or (parent in (%1$s))', implode(',', $items)), ''); } } public function getUrl(int $id): string { $item = $this->getItem($id); return $this->getApp()->site->files . '/files/' . $item['filename']; } public function getLink(int $id): string { $item = $this->getItem($id); return sprintf('<a href="%1$s/files/%2$s" title="%3$s">%4$s</a>', $this->getApp()->site->files, $item['filename'], $item['title'], $item['description']); } public function getHash(string $filename): string { return trim(base64_encode(md5_file($filename, true)), '='); } public function addItem(array $item): int { $realfile = $this->getApp()->paths->files . str_replace('/', DIRECTORY_SEPARATOR, $item['filename']); $item['author'] = $this->getApp()->options->user; $item['posted'] = Str::sqlDate(); $item['hash'] = $this->gethash($realfile); $item['size'] = filesize($realfile); //fix empty props foreach (['mime', 'title', 'description', 'keywords'] as $prop) { if (!isset($item[$prop])) { $item[$prop] = ''; } } return $this->insert($item); } public function insert(array $item): int { $item = $this->escape($item); $id = $this->db->add($item); $this->items[$id] = $item; $this->changed([]); $this->added(['id' => $id]); return $id; } public function escape(array $item): array { foreach (['title', 'description', 'keywords'] as $name) { $item[$name] = Filter::escape(Filter::unescape($item[$name])); } return $item; } public function edit(int $id, string $title, string $description, string $keywords) { $item = $this->getItem($id); if (($item['title'] == $title) && ($item['description'] == $description) && ($item['keywords'] == $keywords)) { return false; } $item['title'] = $title; $item['description'] = $description; $item['keywords'] = $keywords; $item = $this->escape($item); $this->items[$id] = $item; $this->db->updateassoc($item); $this->changed([]); $this->edited(['id' => $id]); return true; } public function delete($id) { if (!$this->itemExists($id)) { return false; } $list = $this->itemsposts->getposts($id); $this->itemsPosts->deleteItem($id); $this->itemsPosts->updatePosts($list, 'files'); $item = $this->getItem($id); if ($item['idperm'] == 0) { @unlink($this->getApp()->paths->files . str_replace('/', DIRECTORY_SEPARATOR, $item['filename'])); } else { @unlink($this->getApp()->paths->files . 'private' . DIRECTORY_SEPARATOR . basename($item['filename'])); $this->getApp()->router->delete('/files/' . $item['filename']); } parent::delete($id); if ((int)$item['preview']) { $this->delete($item['preview']); } if ((int)$item['midle']) { $this->delete($item['midle']); } $this->getdb('imghashes')->delete("id = $id"); $this->changed([]); $this->deleted(['id' => $id]); return true; } public function setContent(int $id, string $content): bool { if (!$this->itemExists($id)) { return false; } $item = $this->getitem($id); $realfile = $this->getApp()->paths->files . str_replace('/', DIRECTORY_SEPARATOR, $item['filename']); if (file_put_contents($realfile, $content)) { $item['hash'] = $this->gethash($realfile); $item['size'] = filesize($realfile); $this->items[$id] = $item; $item['id'] = $id; $this->db->updateassoc($item); } return true; } public function exists(string $filename): bool { return $this->indexOf('filename', $filename); } public function postEdited(Event $event) { $post = Post::i($event->id); $this->itemsPosts->setItems($post->id, $post->files); } } //FilesItems.php namespace litepubl\post; class FilesItems extends \litepubl\core\ItemsPosts { protected function create() { $this->dbversion = true; parent::create(); $this->basename = 'fileitems'; $this->table = 'filesitemsposts'; } } //FileView.php namespace litepubl\post; use litepubl\core\Str; use litepubl\view\Args; use litepubl\view\Theme; use litepubl\view\Vars; /** * View file list * * @property-write callable $onGetFilelist * @property-write callable $onlist * @method array onGetFilelist(array $params) * @method array onlist(array $params) */ class FileView extends \litepubl\core\Events { protected $templates; protected function create() { parent::create(); $this->basename = 'fileview'; $this->addEvents('ongetfilelist', 'onlist'); $this->templates = []; } public function getFiles(): Files { return Files::i(); } public function getFileList(array $list, bool $excerpt, Theme $theme): string { $r = $this->onGetFilelist(['list' => $list, 'excerpt' => $excerpt, 'result' => false]); if ($r['result']) { return $r['result']; } if (!count($list)) { return ''; } $tml = $excerpt ? $this->getTml($theme, 'content.excerpts.excerpt.filelist') : $this->getTml($theme, 'content.post.filelist'); return $this->getList($list, $tml); } public function getTml(Theme $theme, string $basekey): array { if (isset($this->templates[$theme->name][$basekey])) { return $this->templates[$theme->name][$basekey]; } $result = [ 'container' => $theme->templates[$basekey], ]; $key = $basekey . '.'; foreach ($theme->templates as $k => $v) { if (Str::begin($k, $key)) { $result[substr($k, strlen($key)) ] = $v; } } if (!isset($this->templates[$theme->name])) { $this->templates[$theme->name] = []; } $this->templates[$theme->name][$basekey] = $result; return $result; } public function getList(array $list, array $tml): string { if (!count($list)) { return ''; } $this->onList(['list' => $list]); $result = ''; $files = $this->getFiles(); $files->preLoad($list); //sort by media type $items = []; foreach ($list as $id) { if (!isset($files->items[$id])) { continue; } $item = $files->items[$id]; $type = $item['media']; if (isset($tml[$type])) { $items[$type][] = $id; } else { $items['file'][] = $id; } } $theme = Theme::i(); $args = new Args(); $args->count = count($list); $url = $this->getApp()->site->files . '/files/'; $preview = new \ArrayObject([], \ArrayObject::ARRAY_AS_PROPS); $vars = new Vars(); $vars->preview = $preview; $midle = new \ArrayObject([], \ArrayObject::ARRAY_AS_PROPS); $vars->midle = $midle; $index = 0; foreach ($items as $type => $subitems) { $args->subcount = count($subitems); $sublist = ''; foreach ($subitems as $typeindex => $id) { $item = $files->items[$id]; $args->add($item); $args->link = $url . $item['filename']; $args->id = $id; $args->typeindex = $typeindex; $args->index = $index++; $args->preview = ''; $preview->exchangeArray([]); if ($idmidle = (int)$item['midle']) { $midle->exchangeArray($files->getItem($idmidle)); $midle->link = $url . $midle->filename; $midle->json = $this->getJson($idmidle); } else { $midle->exchangeArray([]); $midle->link = ''; $midle->json = ''; } if ((int)$item['preview']) { $preview->exchangeArray($files->getItem($item['preview'])); } elseif ($type == 'image') { $preview->exchangeArray($item); $preview->id = $id; } elseif ($type == 'video') { $args->preview = $theme->parseArg($tml['videos.fallback'], $args); $preview->exchangeArray([]); } if ($preview->count()) { $preview->link = $url . $preview->filename; $args->preview = $theme->parseArg($tml['preview'], $args); } $args->json = $this->getJson($id); $sublist.= $theme->parseArg($tml[$type], $args); } $args->__set($type, $sublist); $result.= $theme->parseArg($tml[$type . 's'], $args); } $args->files = $result; return $theme->parseArg($tml['container'], $args); } public function getFirstImage(array $items): string { $files = $this->getFiles(); foreach ($items as $id) { $item = $files->getItem($id); if (('image' == $item['media']) && ($idpreview = (int)$item['preview'])) { $baseurl = $this->getApp()->site->files . '/files/'; $args = new Args(); $args->add($item); $args->link = $baseurl . $item['filename']; $args->json = $this->getJson($id); $preview = new \ArrayObject($files->getItem($idpreview), \ArrayObject::ARRAY_AS_PROPS); $preview->link = $baseurl . $preview->filename; $midle = new \ArrayObject([], \ArrayObject::ARRAY_AS_PROPS); if ($idmidle = (int)$item['midle']) { $midle->exchangeArray($files->getItem($idmidle)); $midle->link = $baseurl . $midle->filename; $midle->json = $this->getJson($idmidle); } else { $midle->json = ''; } $vars = new Vars(); $vars->preview = $preview; $vars->midle = $midle; $theme = Theme::i(); return $theme->parseArg($theme->templates['content.excerpts.excerpt.firstimage'], $args); } } return ''; } public function getJson(int $id): string { $item = $this->getFiles()->getItem($id); return Str::jsonAttr( [ 'id' => $id, 'link' => $this->getApp()->site->files . '/files/' . $item['filename'], 'width' => $item['width'], 'height' => $item['height'], 'size' => $item['size'], 'midle' => $item['midle'], 'preview' => $item['preview'], ] ); } } //Meta.php namespace litepubl\post; use litepubl\core\Str; class Meta extends \litepubl\core\Item { public static function getInstancename() { return 'postmeta'; } protected function create() { $this->table = 'postsmeta'; } public function getDbversion() { return true; } public function __set($name, $value) { if ($name == 'id') { return $this->setId($value); } $exists = isset($this->data[$name]); if ($exists && ($this->data[$name] == $value)) { return true; } $this->data[$name] = $value; $name = Str::quote($name); $value = Str::quote($value); if ($exists) { $this->db->update("value = $value", "id = $this->id and name = $name"); } else { $this->db->insertrow("(id, name, value) values ($this->id, $name, $value)"); } } public function __unset($name) { $this->remove($name); } //db public function load() { $this->LoadFromDB(); return true; } protected function LoadFromDB() { $db = $this->db; $res = $db->select("id = $this->id"); if (is_object($res)) { while ($r = $res->fetch_assoc()) { $this->data[$r['name']] = $r['value']; } } return true; } protected function SaveToDB() { $db = $this->db; $db->delete("id = $this->id"); foreach ($this->data as $name => $value) { if ($name == 'id') { continue; } $name = Str::quote($name); $value = Str::quote($value); $this->db->insertrow("(id, name, value) values ($this->id, $name, $value)"); } } public function remove($name) { if ($name == 'id') { return; } unset($this->data[$name]); $this->db->delete("id = $this->id and name = '$name'"); } public static function loaditems(array $items) { if (!count($items)) { return; } //exclude already loaded items if (isset(static ::$instances['postmeta'])) { $items = array_diff($items, array_keys(static ::$instances['postmeta'])); if (!count($items)) { return; } } else { static ::$instances['postmeta'] = []; } $instances = & static ::$instances['postmeta']; $db = static::getAppInstance()->db; $db->table = 'postsmeta'; $res = $db->select(sprintf('id in (%s)', implode(',', $items))); while ($row = $db->fetchassoc($res)) { $id = (int)$row['id']; if (!isset($instances[$id])) { $instances[$id] = new static(); $instances[$id]->data['id'] = $id; } $instances[$id]->data[$row['name']] = $row['value']; } return $items; } } //Post.php namespace litepubl\post; use litepubl\core\Arr; use litepubl\core\Str; use litepubl\view\Filter; /** * This is the post base class * * @property int $idschema * @property int $idurl * @property int $parent * @property int $author * @property int $revision * @property int $idperm * @property string $class * @property int $posted timestamp * @property string $title * @property string $title2 * @property string $filtered * @property string $excerpt * @property string $keywords * @property string $description * @property string $rawhead * @property string $moretitle * @property array $categories * @property array $tags * @property array $files * @property string $status enum * @property string $comstatus enum * @property int $pingenabled bool * @property string $password * @property int $commentscount * @property int $pingbackscount * @property int $pagescount * @property string $url * @property int $created timestamp * @property int $modified timestamp * @property array $pages * @property string $rawcontent * @property-read string $instanceName * @property-read string $childTable * @property-read Factory $factory * @property-read View $view * @property-read Meta $meta * @property string $link absolute url * @property-read string isoDate * @property string pubDate * @property-read string sqlDate * @property string $tagNames tags title separated by , * @property string $catNames categories title separated by , * @property-read string $category first category title * @property-read int $idCat first category ID * @property-read bool $hasPages true if has content or comments pages * @property-read int $pagesCount index from 1 * @property-read int $countPages maximum of content or comments pages * @property-read int commentPages * @property-read string lastCommentUrl * @property-read string schemaLink to generate new url */ class Post extends \litepubl\core\Item { use \litepubl\core\Callbacks; protected $childTable; protected $rawTable; protected $pagesTable; protected $childData; protected $cacheData; protected $rawData; protected $factory; private $metaInstance; public static function i($id = 0) { if ($id = (int) $id) { if (isset(static::$instances['post'][$id])) { $result = static::$instances['post'][$id]; } elseif ($result = static::loadPost($id)) { // nothing: set $instances in afterLoad method } else { $result = null; } } else { $result = parent::itemInstance(get_called_class(), $id); } return $result; } public static function loadPost(int $id) { if ($a = static::loadAssoc($id)) { $self = static::newPost($a['class']); $self->setAssoc($a); if ($table = $self->getChildTable()) { $items = static::selectChildItems( $table, [ $id ] ); $self->childData = $items[$id]; unset($self->childData['id']); } $self->afterLoad(); return $self; } return false; } public static function loadAssoc(int $id) { $db = static::getAppInstance()->db; $table = static::getChildTable(); if ($table) { return $db->selectAssoc( "select $db->posts.*, $db->prefix$table.*, $db->urlmap.url as url from $db->posts, $db->prefix$table, $db->urlmap where $db->posts.id = $id and $db->prefix$table.id = $id and $db->urlmap.id = $db->posts.idurl limit 1" ); } else { return $db->selectAssoc( "select $db->posts.*, $db->urlmap.url as url from $db->posts, $db->urlmap where $db->posts.id = $id and $db->urlmap.id = $db->posts.idurl limit 1" ); } } public static function newPost(string $classname): Post { $classname = $classname ? str_replace('-', '\\', $classname) : get_called_class(); return new $classname(); } public static function getInstanceName(): string { return 'post'; } public static function getChildTable(): string { return ''; } public static function selectChildItems(string $table, array $items): array { if (! $table || ! count($items)) { return []; } $db = static::getAppInstance()->db; $childTable = $db->prefix . $table; $list = implode(',', $items); $count = count($items); return $db->res2items($db->query("select $childTable.* from $childTable where id in ($list) limit $count")); } protected function create() { $this->table = 'posts'; $this->rawTable = 'rawposts'; $this->pagesTable = 'pages'; $this->childTable = static::getChildTable(); $options = $this->getApp()->options; $this->data = [ 'id' => 0, 'idschema' => 1, 'idurl' => 0, 'parent' => 0, 'author' => 0, 'revision' => 0, 'idperm' => 0, 'class' => str_replace('\\', '-', get_class($this)), 'posted' => static::ZERODATE, 'title' => '', 'title2' => '', 'filtered' => '', 'excerpt' => '', 'keywords' => '', 'description' => '', 'rawhead' => '', 'moretitle' => '', 'categories' => '', 'tags' => '', 'files' => '', 'status' => 'published', 'comstatus' => $options->comstatus, 'pingenabled' => $options->pingenabled ? '1' : '0', 'password' => '', 'commentscount' => 0, 'pingbackscount' => 0, 'pagescount' => 0 ]; $this->rawData = []; $this->childData = []; $this->cacheData = [ 'posted' => 0, 'categories' => [], 'tags' => [], 'files' => [], 'url' => '', 'created' => 0, 'modified' => 0, 'pages' => [] ]; $this->factory = $this->getfactory(); } public function getFactory() { return Factory::i(); } public function getView(): View { $view = $this->factory->getView(); $view->setPost($this); return $view; } public function __get($name) { if ($name == 'id') { $result = (int) $this->data['id']; } elseif (method_exists($this, $get = 'get' . $name)) { $result = $this->$get(); } elseif (array_key_exists($name, $this->cacheData)) { $result = $this->cacheData[$name]; } elseif (method_exists($this, $get = 'getCache' . $name)) { $result = $this->$get(); $this->cacheData[$name] = $result; } elseif (array_key_exists($name, $this->data)) { $result = $this->data[$name]; } elseif (array_key_exists($name, $this->childData)) { $result = $this->childData[$name]; } elseif (array_key_exists($name, $this->rawData)) { $result = $this->rawData[$name]; } else { $result = parent::__get($name); } return $result; } public function __set($name, $value) { if ($name == 'id') { $this->setId($value); } elseif (method_exists($this, $set = 'set' . $name)) { $this->$set($value); } elseif (array_key_exists($name, $this->cacheData)) { $this->cacheData[$name] = $value; } elseif (array_key_exists($name, $this->data)) { $this->data[$name] = $value; } elseif (array_key_exists($name, $this->childData)) { $this->childData[$name] = $value; } elseif (array_key_exists($name, $this->rawData)) { $this->rawData[$name] = $value; } else { return parent::__set($name, $value); } return true; } public function __isset($name) { return parent::__isset($name) || array_key_exists($name, $this->cacheData) || array_key_exists($name, $this->childData) || array_key_exists($name, $this->rawData) || method_exists($this, 'getCache' . $name); } public function load() { return true; } public function afterLoad() { static::$instances['post'][$this->id] = $this; parent::afterLoad(); } public function setAssoc(array $a) { $this->cacheData = []; foreach ($a as $k => $v) { if (array_key_exists($k, $this->data)) { $this->data[$k] = $v; } elseif (array_key_exists($k, $this->childData)) { $this->childData[$k] = $v; } elseif (array_key_exists($k, $this->rawData)) { $this->rawData[$k] = $v; } else { $this->cacheData[$k] = $v; } } } public function save() { if ($this->lockcount > 0) { return; } $this->saveToDB(); } protected function saveToDB() { if (! $this->id) { return $this->add(); } $this->db->updateAssoc($this->data); $this->modified = time(); $this->getDB($this->rawTable)->setValues($this->id, $this->rawData); if ($this->childTable) { $this->getDB($this->childTable)->setValues($this->id, $this->childData); } } public function add(): int { $a = $this->data; unset($a['id']); $id = $this->db->add($a); $rawData = $this->prepareRawData(); $rawData['id'] = $id; $this->getDB($this->rawTable)->insert($rawData); $this->setId($id); $this->savePages(); if ($this->childTable) { $childData = $this->childData; $childData['id'] = $id; $this->getDB($this->childTable)->insert($childData); } $this->idurl = $this->createUrl(); $this->db->setValue($id, 'idurl', $this->idurl); $this->triggerOnId(); return $id; } protected function prepareRawData() { if (! $this->created) { $this->created = time(); } if (! $this->modified) { $this->modified = time(); } if (! isset($this->rawData['rawcontent'])) { $this->rawData['rawcontent'] = ''; } return $this->rawData; } public function createUrl() { return $this->getApp()->router->add($this->url, get_class($this), (int) $this->id); } public function onId(callable $callback) { $this->addCallback('onid', $callback); } protected function triggerOnId() { $this->triggerCallback('onid'); $this->clearCallbacks('onid'); if (isset($this->metaInstance)) { $this->metaInstance->id = $this->id; $this->metaInstance->save(); } } public function free() { if (isset($this->metaInstance)) { $this->metaInstance->free(); } parent::free(); } public function getComments() { return $this->factory->getcomments($this->id); } public function getPingbacks() { return $this->factory->getpingbacks($this->id); } public function getMeta() { if (! isset($this->metaInstance)) { $this->metaInstance = $this->factory->getmeta($this->id); } return $this->metaInstance; } // props protected function setDataProp($name, $value, $sql) { $this->cacheData[$name] = $value; if (array_key_exists($name, $this->data)) { $this->data[$name] = $sql; } elseif (array_key_exists($name, $this->childData)) { $this->childData[$name] = $sql; } elseif (array_key_exists($name, $this->rawData)) { $this->rawData[$name] = $sql; } } protected function setArrProp($name, array $list) { Arr::clean($list); $this->setDataProp($name, $list, implode(',', $list)); } protected function setBoolProp($name, $value) { $this->setDataProp($name, $value, $value ? '1' : '0'); } // cache props protected function getArrProp($name) { if ($s = $this->data[$name]) { return explode(',', $s); } else { return []; } } protected function getCacheCategories() { return $this->getArrProp('categories'); } protected function getCacheTags() { return $this->getArrProp('tags'); } protected function getCacheFiles() { return $this->getArrProp('files'); } public function setFiles(array $list) { $this->setArrProp('files', $list); } public function setCategories(array $list) { $this->setArrProp('categories', $list); } public function setTags(array $list) { $this->setArrProp('tags', $list); } protected function getCachePosted() { return $this->data['posted'] == static::ZERODATE ? 0 : strtotime($this->data['posted']); } public function setPosted($timestamp) { $this->data['posted'] = Str::sqlDate($timestamp); $this->cacheData['posted'] = $timestamp; } protected function getCacheModified() { return ! isset($this->rawData['modified']) || $this->rawData['modified'] == static::ZERODATE ? 0 : strtotime($this->rawData['modified']); } public function setModified($timestamp) { $this->rawData['modified'] = Str::sqlDate($timestamp); $this->cacheData['modified'] = $timestamp; } protected function getCacheCreated() { return ! isset($this->rawData['created']) || $this->rawData['created'] == static::ZERODATE ? 0 : strtotime($this->rawData['created']); } public function setCreated($timestamp) { $this->rawData['created'] = Str::sqlDate($timestamp); $this->cacheData['created'] = $timestamp; } public function Getlink() { return $this->getApp()->site->url . $this->url; } public function Setlink($link) { if ($a = @parse_url($link)) { if (empty($a['query'])) { $this->url = $a['path']; } else { $this->url = $a['path'] . '?' . $a['query']; } } } public function setTitle($title) { $this->data['title'] = Filter::escape(Filter::unescape($title)); } public function getIsoDate() { return date('c', $this->posted); } public function getPubDate() { return date('r', $this->posted); } public function setPubDate($date) { $this->setDateProp('posted', strtotime($date)); } public function getSqlDate() { return $this->data['posted']; } public function getTagnames() { if (count($this->tags)) { $tags = $this->factory->tags; return implode(', ', $tags->getnames($this->tags)); } return ''; } public function setTagNames(string $names) { $tags = $this->factory->tags; $this->tags = $tags->createnames($names); } public function getCatnames() { if (count($this->categories)) { $categories = $this->factory->categories; return implode(', ', $categories->getnames($this->categories)); } return ''; } public function setCatNames($names) { $categories = $this->factory->categories; $catItems = $categories->createnames($names); if (! count($catItems)) { $defaultid = $categories->defaultid; if ($defaultid > 0) { $catItems[] = $defaultid; } } $this->categories = $catItems; } public function getCategory(): string { if ($idcat = $this->getidcat()) { return $this->factory->categories->getName($idcat); } return ''; } public function getIdCat(): int { if (($cats = $this->categories) && count($cats)) { return $cats[0]; } return 0; } public function checkRevision() { $this->updateRevision((int) $this->factory->posts->revision); } public function updateRevision($value) { if ($value != $this->revision) { $this->updateFiltered(); $posts = $this->factory->posts; $this->revision = (int) $posts->revision; if ($this->id > 0) { $this->save(); } } } public function updateFiltered() { Filter::i()->filterPost($this, $this->rawcontent); } public function setRawContent($s) { $this->rawData['rawcontent'] = $s; } public function getRawContent() { if (isset($this->rawData['rawcontent'])) { return $this->rawData['rawcontent']; } if (! $this->id) { return ''; } $this->rawData = $this->getDB($this->rawTable)->getItem($this->id); unset($this->rawData['id']); return $this->rawData['rawcontent']; } public function getPage(int $i) { if (isset($this->cacheData['pages'][$i])) { return $this->cacheData['pages'][$i]; } if ($this->id > 0) { if ($r = $this->getdb($this->pagesTable)->getAssoc("(id = $this->id) and (page = $i) limit 1")) { $s = $r['content']; } else { $s = false; } $this->cacheData['pages'][$i] = $s; return $s; } return false; } public function addPage($s) { $this->cacheData['pages'][] = $s; $this->data['pagescount'] = count($this->cacheData['pages']); if ($this->id > 0) { $this->getdb($this->pagesTable)->insert( [ 'id' => $this->id, 'page' => $this->data['pagescount'] - 1, 'content' => $s ] ); } } public function deletePages() { $this->cacheData['pages'] = []; $this->data['pagescount'] = 0; if ($this->id > 0) { $this->getdb($this->pagesTable)->idDelete($this->id); } } public function savePages() { if (isset($this->cacheData['pages'])) { $db = $this->getDB($this->pagesTable); foreach ($this->cacheData['pages'] as $index => $content) { $db->insert( [ 'id' => $this->id, 'page' => $index, 'content' => $content ] ); } } } public function getHasPages(): bool { return ($this->pagescount > 1) || ($this->commentpages > 1); } public function getPagesCount() { return $this->data['pagescount'] + 1; } public function getCountPages() { return max($this->pagescount, $this->commentpages); } public function getCommentPages() { $options = $this->getApp()->options; if (! $options->commentpages || ($this->commentscount <= $options->commentsperpage)) { return 1; } return ceil($this->commentscount / $options->commentsperpage); } public function getLastCommentUrl() { $c = $this->commentpages; $url = $this->url; if (($c > 1) && ! $this->getApp()->options->comments_invert_order) { $url = rtrim($url, '/') . "/page/$c/"; } return $url; } public function clearCache() { $this->getApp()->cache->clearUrl($this->url); } public function getSchemalink(): string { return 'post'; } public function setContent($s) { if (! is_string($s)) { $this->error('Error! Post content must be string'); } $this->rawcontent = $s; Filter::i()->filterpost($this, $s); } } //Posts.php namespace litepubl\post; use litepubl\core\Cron; use litepubl\core\Str; use litepubl\utils\LinkGenerator; use litepubl\view\Schemes; /** * Main class to manage posts * * @property int $archivescount * @property int $revision * @property bool $syncmeta * @property-write callable $edited * @property-write callable $changed * @property-write callable $singleCron * @property-write callable $onSelect * @method array edited(array $params) * @method array changed(array $params) * @method array singleCron(array $params) * @method array onselect(array $params) */ class Posts extends \litepubl\core\Items { const POSTCLASS = __NAMESPACE__ . '/Post'; public $itemcoclasses; public $archives; public $rawtable; public $childTable; public static function unsub($obj) { static ::i()->unbind($obj); } protected function create() { $this->dbversion = true; parent::create(); $this->table = 'posts'; $this->childTable = ''; $this->rawtable = 'rawposts'; $this->basename = 'posts/index'; $this->addEvents('edited', 'changed', 'singlecron', 'onselect'); $this->data['archivescount'] = 0; $this->data['revision'] = 0; $this->data['syncmeta'] = false; $this->addmap('itemcoclasses', []); } public function getItem($id) { if ($result = Post::i($id)) { return $result; } $this->error("Item $id not found in class " . get_class($this)); } public function findItems(string $where, string $limit): array { if (isset(Post::$instances['post']) && (count(Post::$instances['post']))) { $result = $this->db->idSelect($where . ' ' . $limit); $this->loadItems($result); return $result; } else { return $this->select($where, $limit); } } public function loadItems(array $items) { //exclude already loaded items if (!isset(Post::$instances['post'])) { Post::$instances['post'] = []; } $loaded = array_keys(Post::$instances['post']); $newitems = array_diff($items, $loaded); if (!count($newitems)) { return $items; } $newitems = $this->select(sprintf('%s.id in (%s)', $this->thistable, implode(',', $newitems)), 'limit ' . count($newitems)); return array_merge($newitems, array_intersect($loaded, $items)); } public function setAssoc(array $items) { if (!count($items)) { return []; } $result = []; $fileitems = []; foreach ($items as $a) { $post = Post::newPost($a['class']); $post->setAssoc($a); $post->afterLoad(); $result[] = $post->id; $f = $post->files; if (count($f)) { $fileitems = array_merge($fileitems, array_diff($f, $fileitems)); } } if ($this->syncmeta) { Meta::loadItems($result); } if (count($fileitems)) { Files::i()->preLoad($fileitems); } $this->onSelect(['items' => $result]); return $result; } public function select(string $where, string $limit): array { $db = $this->getApp()->db; if ($this->childTable) { $childTable = $db->prefix . $this->childTable; return $this->setAssoc( $db->res2items( $db->query( "select $db->posts.*, $childTable.*, $db->urlmap.url as url from $db->posts, $childTable, $db->urlmap where $where and $db->posts.id = $childTable.id and $db->urlmap.id = $db->posts.idurl $limit" ) ) ); } $items = $db->res2items( $db->query( "select $db->posts.*, $db->urlmap.url as url from $db->posts, $db->urlmap where $where and $db->urlmap.id = $db->posts.idurl $limit" ) ); if (!count($items)) { return []; } $subclasses = []; foreach ($items as $id => $item) { if (empty($item['class'])) { $items[$id]['class'] = static ::POSTCLASS; } elseif ($item['class'] != static ::POSTCLASS) { $subclasses[$item['class']][] = $id; } } foreach ($subclasses as $class => $list) { $class = str_replace('-', '\\', $class); $childDataItems = $class::selectChildItems($class::getChildTable(), $list); foreach ($childDataItems as $id => $childData) { $items[$id] = array_merge($items[$id], $childData); } } return $this->setAssoc($items); } public function getCount() { return $this->db->getcount("status<> 'deleted'"); } public function getChildsCount($where) { if (!$this->childTable) { return 0; } $db = $this->getApp()->db; $childTable = $db->prefix . $this->childTable; $res = $db->query( "SELECT COUNT($db->posts.id) as count FROM $db->posts, $childTable where $db->posts.status <> 'deleted' and $childTable.id = $db->posts.id $where" ); if ($res && ($r = $db->fetchassoc($res))) { return $r['count']; } return 0; } private function beforeChange($post) { $post->title = trim($post->title); $post->modified = time(); $post->revision = $this->revision; $post->class = str_replace('\\', '-', ltrim(get_class($post), '\\')); if (($post->status == 'published') && ($post->posted > time())) { $post->status = 'future'; } elseif (($post->status == 'future') && ($post->posted <= time())) { $post->status = 'published'; } } public function add(Post $post): int { $this->beforeChange($post); if (!$post->posted) { $post->posted = time(); } if ($post->posted <= time()) { if ($post->status == 'future') { $post->status = 'published'; } } else { if ($post->status == 'published') { $post->status = 'future'; } } if ($post->idschema == 1) { $schemes = Schemes::i(); if (isset($schemes->defaults['post'])) { $post->data['idschema'] = $schemes->defaults['post']; } } $post->url = LinkGenerator::i()->addUrl($post, $post->schemaLink); $id = $post->add(); $this->updated($post); $this->added(['id' => $id]); $this->changed([]); $this->getApp()->cache->clear(); return $id; } public function edit(Post $post) { $this->beforeChange($post); $linkgen = LinkGenerator::i(); $linkgen->editurl($post, $post->schemaLink); if ($post->posted <= time()) { if ($post->status == 'future') { $post->status = 'published'; } } else { if ($post->status == 'published') { $post->status = 'future'; } } $this->lock(); $post->save(); $this->updated($post); $this->unlock(); $this->edited(['id' => $post->id]); $this->changed([]); $this->getApp()->cache->clear(); } public function delete($id) { if (!$this->itemExists($id)) { return false; } $this->db->setvalue($id, 'status', 'deleted'); if ($this->childTable) { $db = $this->getdb($this->childTable); $db->delete("id = $id"); } $this->lock(); $this->PublishFuture(); $this->UpdateArchives(); $this->unlock(); $this->deleted(['id' => $id]); $this->changed([]); $this->getApp()->cache->clear(); return true; } public function updated(Post $post) { $this->PublishFuture(); $this->UpdateArchives(); Cron::i()->add('single', get_class($this), 'dosinglecron', $post->id); } public function UpdateArchives() { $this->archivescount = $this->db->getcount("status = 'published' and posted <= '" . Str::sqlDate() . "'"); } public function doSingleCron($id) { $this->PublishFuture(); Theme::$vars['post'] = Post::i($id); $this->singleCron(['id' => $id]); unset(Theme::$vars['post']); } public function hourcron() { $this->PublishFuture(); } private function publish($id) { $post = Post::i($id); $post->status = 'published'; $this->edit($post); } public function PublishFuture() { if ($list = $this->db->idselect(sprintf('status = \'future\' and posted <= \'%s\' order by posted asc', Str::sqlDate()))) { foreach ($list as $id) { $this->publish($id); } } } public function getRecent($author, $count) { $author = (int)$author; $where = "status != 'deleted'"; if ($author > 1) { $where.= " and author = $author"; } return $this->findItems($where, ' order by posted desc limit ' . (int)$count); } public function getPage(int $author, int $page, int $perpage, bool $invertorder): array { $from = ($page - 1) * $perpage; $t = $this->thistable; $where = "$t.status = 'published'"; if ($author > 1) { $where.= " and $t.author = $author"; } $order = $invertorder ? 'asc' : 'desc'; return $this->findItems($where, " order by $t.posted $order limit $from, $perpage"); } public function stripDrafts(array $items): array { if (count($items) == 0) { return []; } $list = implode(',', $items); $t = $this->thistable; return $this->db->idSelect("$t.status = 'published' and $t.id in ($list)"); } public function addRevision(): int { $this->data['revision']++; $this->save(); $this->getApp()->cache->clear(); return $this->data['revision']; } public function getSitemap($from, $count) { return $this->externalfunc( __class__, 'Getsitemap', [ $from, $count ] ); } } //View.php namespace litepubl\post; use litepubl\comments\Templates; use litepubl\core\Context; use litepubl\core\Str; use litepubl\view\Args; use litepubl\view\Lang; use litepubl\view\MainView; use litepubl\view\Schema; use litepubl\view\Theme; /** * Post view * * @property-write callable $beforeContent * @property-write callable $afterContent * @property-write callable $beforeExcerpt * @property-write callable $afterExcerpt * @property-write callable $onHead * @property-write callable $onTags * @method array beforeContent(array $params) * @method array afterContent(array $params) * @method array beforeExcerpt(array $params) * @method array afterExcerpt(array $params) * @method array onHead(array $params) * @method array onTags(array $params) */ class View extends \litepubl\core\Events implements \litepubl\view\ViewInterface { use \litepubl\core\PoolStorageTrait; public $post; public $context; private $prevPost; private $nextPost; private $themeInstance; protected function create() { parent::create(); $this->basename = 'postview'; $this->addEvents('beforecontent', 'aftercontent', 'beforeexcerpt', 'afterexcerpt', 'onhead', 'ontags'); $this->table = 'posts'; } public function setPost(Post $post) { $this->post = $post; $this->themeInstance = null; } public function getView() { return $this; } public function __get($name) { if (method_exists($this, $get = 'get' . $name)) { $result = $this->$get(); } else { switch ($name) { case 'catlinks': $result = $this->get_taglinks('categories', false); break; case 'taglinks': $result = $this->get_taglinks('tags', false); break; case 'excerptcatlinks': $result = $this->get_taglinks('categories', true); break; case 'excerpttaglinks': $result = $this->get_taglinks('tags', true); break; default: if (isset($this->post->$name)) { $result = $this->post->$name; } else { $result = parent::__get($name); } } } return $result; } public function __set($name, $value) { if (parent::__set($name, $value)) { return true; } if (isset($this->post->$name)) { $this->post->$name = $value; return true; } return false; } public function __call($name, $args) { if (method_exists($this->post, $name)) { return call_user_func_array([$this->post, $name], $args); } else { return parent::__call($name, $args); } } public function getPrev() { if (!is_null($this->prevPost)) { return $this->prevPost; } $this->prevPost = false; if ($id = $this->db->findid("status = 'published' and posted < '$this->sqldate' order by posted desc")) { $this->prevPost = Post::i($id); } return $this->prevPost; } public function getNext() { if (!is_null($this->nextPost)) { return $this->nextPost; } $this->nextPost = false; if ($id = $this->db->findid("status = 'published' and posted > '$this->sqldate' order by posted asc")) { $this->nextPost = Post::i($id); } return $this->nextPost; } public function getTheme(): Theme { if (!$this->themeInstance) { $this->themeInstance = $this->post ? $this->schema->theme : Theme::context(); } $this->themeInstance->setvar('post', $this); return $this->themeInstance; } public function setTheme(Theme $theme) { $this->themeInstance = $theme; } public function parseTml(string $path): string { $theme = $this->theme; return $theme->parse($theme->templates[$path]); } public function getExtra() { $theme = $this->theme; return $theme->parse($theme->extratml); } public function getBookmark() { return $this->theme->parse($this->theme->templates['content.post.bookmark']); } public function getRssComments(): string { return $this->getApp()->site->url . "/comments/$this->id.xml"; } public function getIdImage(): int { if (!count($this->files)) { return 0; } $files = $this->factory->files; foreach ($this->files as $id) { $item = $files->getItem($id); if ('image' == $item['media']) { return $id; } } return 0; } public function getImage(): string { if ($id = $this->getIdImage()) { return $this->factory->files->getUrl($id); } return ''; } public function getThumb(): string { if (!count($this->files)) { return ''; } $files = $this->factory->files; foreach ($this->files as $id) { $item = $files->getItem($id); if ((int)$item['preview']) { return $files->getUrl($item['preview']); } } return ''; } public function getFirstImage(): string { $items = $this->files; if (count($items)) { return $this->factory->fileView->getFirstImage($items); } return ''; } //template protected function get_taglinks($name, $excerpt) { $items = $this->__get($name); if (!count($items)) { return ''; } $theme = $this->theme; $tmlpath = $excerpt ? 'content.excerpts.excerpt' : 'content.post'; $tmlpath.= $name == 'tags' ? '.taglinks' : '.catlinks'; $tmlitem = $theme->templates[$tmlpath . '.item']; $tags = Str::begin($name, 'tag') ? $this->factory->tags : $this->factory->categories; $tags->loaditems($items); $args = new Args(); $list = []; foreach ($items as $id) { if ($id && ($item = $tags->getItem($id))) { $args->add($item); $list[] = $theme->parseArg($tmlitem, $args); } } $args->items = ' ' . implode($theme->templates[$tmlpath . '.divider'], $list); $result = $theme->parseArg($theme->templates[$tmlpath], $args); $r = $this->onTags(['tags' => $tags, 'excerpt' => $excerpt, 'content' => $result]); return $r['content']; } public function getDate(): string { return Lang::date($this->posted, $this->theme->templates['content.post.date']); } public function getExcerptDate(): string { return Lang::date($this->posted, $this->theme->templates['content.excerpts.excerpt.date']); } public function getDay(): string { return date($this->posted, 'D'); } public function getMonth(): string { return Lang::date($this->posted, 'M'); } public function getYear(): string { return date($this->posted, 'Y'); } public function getMoreLink(): string { if ($this->moretitle) { return $this->parsetml('content.excerpts.excerpt.morelink'); } return ''; } public function request(Context $context) { $app = $this->getApp(); if ($this->status != 'published') { if (!$app->options->show_draft_post) { $context->response->status = 404; return; } $groupname = $app->options->group; if (($groupname == 'admin') || ($groupname == 'editor')) { return; } if ($this->author == $app->options->user) { return; } $context->response->status = 404; return; } $this->context = $context; } public function getPage(): int { return $this->context->request->page; } public function getTitle(): string { return $this->post->title; } public function getHead(): string { $result = $this->rawhead; MainView::i()->ltoptions['idpost'] = $this->id; $theme = $this->theme; $result.= $theme->templates['head.post']; if ($prev = $this->prev) { Theme::$vars['prev'] = $prev; $result.= $theme->templates['head.post.prev']; } if ($next = $this->next) { Theme::$vars['next'] = $next; $result.= $theme->templates['head.post.next']; } if ($this->hascomm) { Lang::i('comment'); $result.= $theme->templates['head.post.rss']; } $result = $theme->parse($result); $r = $this->onHead(['post' => $this->post, 'content' => $result]); return $r['content']; } public function getKeywords(): string { if ($result = $this->post->keywords) { return $result; } else { return $this->Gettagnames(); } } public function getDescription(): string { return $this->post->description; } public function getIdSchema(): int { return $this->post->idschema; } public function setIdSchema(int $id) { if ($id != $this->idschema) { $this->post->idschema = $id; if ($this->id) { $this->post->db->setvalue($this->id, 'idschema', $id); } } } public function getSchema(): Schema { return Schema::getSchema($this); } //to override schema in post, id schema not changed public function getFileList(): string { $items = $this->files; if (!count($items) || (($this->page > 1) && $this->getApp()->options->hidefilesonpage)) { return ''; } $fileView = $this->factory->fileView; return $fileView->getFileList($items, false, $this->theme); } public function getExcerptFileList(): string { $items = $this->files; if (count($items) == 0) { return ''; } $fileView = $this->factory->fileView; return $fileView->getFileList($items, true, $this->theme); } public function getIndexTml() { $theme = $this->theme; if (!empty($theme->templates['index.post'])) { return $theme->templates['index.post']; } return false; } public function getCont(): string { return $this->parsetml('content.post'); } public function getRssLink(): string { if ($this->hascomm) { return $this->parseTml('content.post.rsslink'); } return ''; } public function onRssItem($item) { } public function getRss(): string { $this->getApp()->getLogManager()->trace('get rss deprecated post property'); return $this->post->excerpt; } public function getPrevNext(): string { $prev = ''; $next = ''; $theme = $this->theme; if ($prevpost = $this->prev) { Theme::$vars['prevpost'] = $prevpost; $prev = $theme->parse($theme->templates['content.post.prevnext.prev']); } if ($nextpost = $this->next) { Theme::$vars['nextpost'] = $nextpost; $next = $theme->parse($theme->templates['content.post.prevnext.next']); } if (($prev == '') && ($next == '')) { return ''; } $result = strtr( $theme->parse($theme->templates['content.post.prevnext']), [ '$prev' => $prev, '$next' => $next ] ); unset(Theme::$vars['prevpost'], Theme::$vars['nextpost']); return $result; } public function getCommentsLink(): string { $tml = sprintf('<a href="%s%s#comments">%%s</a>', $this->getApp()->site->url, $this->getlastcommenturl()); if (($this->comstatus == 'closed') || !$this->getApp()->options->commentspool) { if (($this->commentscount == 0) && (($this->comstatus == 'closed'))) { return ''; } return sprintf($tml, $this->getcmtcount()); } //inject php code return sprintf('<?php echo litepubl\comments\Pool::i()->getLink(%d, \'%s\'); ?>', $this->id, $tml); } public function getCmtCount(): string { $l = Lang::i()->ini['comment']; switch ($this->commentscount) { case 0: return $l[0]; case 1: return $l[1]; default: return sprintf($l[2], $this->commentscount); } } public function getTemplateComments(): string { $result = ''; $countpages = $this->countpages; if ($countpages > 1) { $result.= $this->theme->getpages($this->url, $this->page, $countpages); } if (($this->commentscount > 0) || ($this->comstatus != 'closed') || ($this->pingbackscount > 0)) { if (($countpages > 1) && ($this->commentpages < $this->page)) { $result.= $this->getCommentsLink(); } else { $result.= Templates::i()->getcomments($this); } } return $result; } public function getHasComm(): bool { return ($this->comstatus != 'closed') && ((int)$this->commentscount > 0); } public function getAnnounce(string $announceType): string { $tmlKey = 'content.excerpts.' . ($announceType == 'excerpt' ? 'excerpt' : $announceType . '.excerpt'); return $this->parseTml($tmlKey); } public function getExcerptContent(): string { $this->post->checkRevision(); $r = $this->beforeExcerpt(['post' => $this->post, 'content' => $this->excerpt]); $result = $this->replaceMore($r['content'], true); if ($this->getApp()->options->parsepost) { $result = $this->theme->parse($result); } $r = $this->afterExcerpt(['post' => $this->post, 'content' => $result]); return $r['content']; } public function replaceMore(string $content, string $excerpt): string { $more = $this->parseTml($excerpt ? 'content.excerpts.excerpt.morelink' : 'content.post.more'); $tag = '<!--more-->'; if (strpos($content, $tag)) { return str_replace($tag, $more, $content); } else { return $excerpt ? $content : $more . $content; } } protected function getTeaser(): string { $content = $this->filtered; $tag = '<!--more-->'; if ($i = strpos($content, $tag)) { $content = substr($content, $i + strlen($tag)); if (!Str::begin($content, '<p>')) { $content = '<p>' . $content; } return $content; } return ''; } protected function getContentPage(int $page): string { $result = ''; if ($page == 1) { $result.= $this->filtered; $result = $this->replaceMore($result, false); } elseif ($s = $this->post->getPage($page - 2)) { $result.= $s; } elseif ($page <= $this->commentpages) { } else { $result.= Lang::i()->notfound; } return $result; } public function getContent(): string { $this->post->checkRevision(); $r = $this->beforeContent(['post' => $this->post, 'content' => '']); $result = $r['content']; $result.= $this->getContentPage($this->page); if ($this->getApp()->options->parsepost) { $result = $this->theme->parse($result); } $r = $this->afterContent(['post' => $this->post, 'content' => $result]); return $r['content']; } //author protected function getAuthorName(): string { return $this->getusername($this->author, false); } protected function getAuthorLink() { return $this->getusername($this->author, true); } protected function getUserName($id, $link) { if ($id <= 1) { if ($link) { return sprintf('<a href="%s/" rel="author" title="%2$s">%2$s</a>', $this->getApp()->site->url, $this->getApp()->site->author); } else { return $this->getApp()->site->author; } } else { $users = $this->factory->users; if (!$users->itemExists($id)) { return ''; } $item = $users->getitem($id); if (!$link || ($item['website'] == '')) { return $item['name']; } return sprintf('<a href="%s/users.htm%sid=%s">%s</a>', $this->getApp()->site->url, $this->getApp()->site->q, $id, $item['name']); } } public function getAuthorPage() { $id = $this->author; if ($id <= 1) { return sprintf('<a href="%s/" rel="author" title="%2$s">%2$s</a>', $this->getApp()->site->url, $this->getApp()->site->author); } else { $pages = $this->factory->userpages; if (!$pages->itemExists($id)) { return ''; } $pages->id = $id; if ($pages->url == '') { return ''; } return sprintf('<a href="%s%s" title="%3$s" rel="author"><%3$s</a>', $this->getApp()->site->url, $pages->url, $pages->name); } } }
litepubl/cms
lib/post/kernel.php
PHP
mit
69,969
#ifndef GLMESH_H #define GLMESH_H #include <GLplus.hpp> namespace tinyobj { struct shape_t; } // end namespace tinyobj namespace GLmesh { class StaticMesh { std::shared_ptr<GLplus::Buffer> mpPositions; std::shared_ptr<GLplus::Buffer> mpTexcoords; std::shared_ptr<GLplus::Buffer> mpNormals; std::shared_ptr<GLplus::Buffer> mpIndices; size_t mVertexCount = 0; std::shared_ptr<GLplus::Texture2D> mpDiffuseTexture; public: void LoadShape(const tinyobj::shape_t& shape); void Render(GLplus::Program& program) const; }; } // end namespace GLmesh #endif // GLMESH_H
nguillemot/LD48-Beneath-The-Surface
GLmesh/include/GLmesh.hpp
C++
mit
605
github-org-feed-page ==================== Static site for your orgs gh-pages that shows off a feed of great things your team have been doing on github recently
pimterry/github-org-feed-page
README.md
Markdown
mit
162
# 888. Fair Candy Swap Difficulty: Easy https://leetcode.com/problems/fair-candy-swap/ Alice and Bob have candy bars of different sizes: A[i] is the size of the i-th bar of candy that Alice has, and B[j] is the size of the j-th bar of candy that Bob has. Since they are friends, they would like to exchange one candy bar each so that after the exchange, they both have the same total amount of candy. (The total amount of candy a person has is the sum of the sizes of candy bars they have.) Return an integer array ans where ans[0] is the size of the candy bar that Alice must exchange, and ans[1] is the size of the candy bar that Bob must exchange. If there are multiple answers, you may return any one of them. It is guaranteed an answer exists. **Example 1:** ``` Input: A = [1,1], B = [2,2] Output: [1,2] ``` **Example 2:** ``` Input: A = [1,2], B = [2,3] Output: [1,2] ``` **Example 3:** ``` Input: A = [2], B = [1,3] Output: [2,3] ``` **Example 4:** ``` Input: A = [1,2,5], B = [2,4] Output: [5,4] ``` **Note:** * 1 <= A.length <= 10000 * 1 <= B.length <= 10000 * 1 <= A[i] <= 100000 * 1 <= B[i] <= 100000 * It is guaranteed that Alice and Bob have different total amounts of candy. * It is guaranteed there exists an answer. Companies: Fidessa Related Topics: Array
jiadaizhao/LeetCode
0801-0900/0888-Fair Candy Swap/README.md
Markdown
mit
1,289
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>smooth scroll polyfill</title> <meta name="viewport" content="width=device-width"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/4.1.1/normalize.min.css"> <link href='https://fonts.googleapis.com/css?family=Roboto+Condensed:400,700' rel='stylesheet' type='text/css'> <!-- rAF polyfill --> <script> // http://paulirish.com/2011/requestanimationframe-for-smart-animating/ // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating // requestAnimationFrame polyfill by Erik Möller. fixes from Paul Irish and Tino Zijdel // MIT license (function() { var lastTime = 0; var vendors = ['ms', 'moz', 'webkit', 'o']; for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame']; window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame']; } if (!window.requestAnimationFrame) window.requestAnimationFrame = function(callback, element) { var currTime = new Date().getTime(); var timeToCall = Math.max(0, 16 - (currTime - lastTime)); var id = window.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; if (!window.cancelAnimationFrame) window.cancelAnimationFrame = function(id) { clearTimeout(id); }; }()); </script> <!-- smooth scroll behavior polyfill --> <script src="src/smoothscroll.js"></script> <!-- site styles --> <style> body { background-color: #fefefe; color: #212121; font-family: 'Roboto Condensed', Arial, sans-serif; font-size: 20px; text-rendering: optimizeLegibility; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } .container { margin: 0 auto; max-width: 800px; padding: 40px; overflow: hidden; position: relative; } a { color: #f44336; text-decoration: none; } a:hover { text-decoration: underline; } header { background-color: #f44336; color: #fefefe; } .featured { background-color: #efefef; } .featured__link { display: inline-block; margin-right: 45px; } h1 { font-size: 2.75em; font-weight: 400; letter-spacing: -.03em; line-height: 1em; } p { line-height: 1.5em; } small { font-weight: 400; } code { font-family: Menlo, monospace; font-size: 15px; vertical-align: middle; } pre { overflow: auto; width: 100%; } pre code { font-size: 14px; } .actions { margin-top: 30px; } .btn { background-color: #f44336; border-width: 0; border-radius: 4px; color: #fefefe; cursor: pointer; font-weight: 700; padding: 6px 12px; text-transform: uppercase; transition: all .35s ease; } .btn:active { background-color: #d32f2f; } .scrollable-parent { background-color: #efefef; border-radius: 4px; margin: 20px 0 0; max-height: 200px; overflow: scroll; padding: 30px 50px; } .hello { text-align: center; } footer { background-color: #404040; color: #fefefe; font-size: 18px; } footer a { color: inherit; } </style> </head> <body> <header> <div class="container"> <h1>smooth scroll polyfill</h1> </div> </header> <main class="featured"> <div class="container"> <p>The <strong>Scroll Behavior</strong> specification has been introduced as an extension of the <strong>Window</strong> interface to allow for the developer to opt in to native smooth scrolling.</p> <p>Check the repository on <a href="https://github.com/iamdustan/smoothscroll">GitHub</a> or download the polyfill as an <a href="https://npmjs.org/smoothscroll-polyfill">npm module</a>.</p> </div> </main> <section class="sample sample-scrollToBottom"> <div class="container"> <h2>window.scroll <small>or</small> window.scrollTo</h2> <pre><code>window.scroll({ top: 2500, left: 0, behavior: 'smooth' });</code></pre> <div class="actions"> <button class="btn js-scroll-to-bottom">scroll to bottom</button> </div> </div> </section> <section class="sample sample-scrollBy"> <div class="container"> <h2>window.scrollBy</h2> <pre><code>window.scrollBy({ top: 100, left: 0, behavior: 'smooth' });</code></pre> <div class="actions"> <button class="btn js-scroll-by">scroll by 100 pixels</button> </div> </div> </section> <section class="sample sample-scrollBack"> <div class="container"> <h2>window.scrollBy</h2> <pre><code>window.scrollBy({ top: -100, left: 0, behavior: 'smooth' });</code></pre> <div class="actions"> <button class="btn js-scroll-back">scroll back 100 pixels</button> </div> </div> </section> <section class=" sample sample--scrollIntoView"> <div class="container"> <h2>element.scrollIntoView</h2> <pre><code>document.querySelector('.hello').scrollIntoView({ behavior: 'smooth' });</code></pre> <div class="actions"> <button class="btn js-scroll-into-hello">Scroll into view</button> </div> <article class="scrollable-parent"> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Qui iure obcaecati, repudiandae aspernatur cumque recusandae adipisci consequuntur maiores, quo in nulla ratione facere distinctio beatae, quae consequatur ab labore dolorum.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Qui iure obcaecati, repudiandae aspernatur cumque recusandae adipisci consequuntur maiores, quo in nulla ratione facere distinctio beatae, quae consequatur ab labore dolorum.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Qui iure obcaecati, repudiandae aspernatur cumque recusandae adipisci consequuntur maiores, quo in nulla ratione facere distinctio beatae, quae consequatur ab labore dolorum.</p> <h3 class="hello"><em>hello!</em></h3> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Qui iure obcaecati, repudiandae aspernatur cumque recusandae adipisci consequuntur maiores, quo in nulla ratione facere distinctio beatae, quae consequatur ab labore dolorum.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Qui iure obcaecati, repudiandae aspernatur cumque recusandae adipisci consequuntur maiores, quo in nulla ratione facere distinctio beatae, quae consequatur ab labore dolorum.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Qui iure obcaecati, repudiandae aspernatur cumque recusandae adipisci consequuntur maiores, quo in nulla ratione facere distinctio beatae, quae consequatur ab labore dolorum.</p> </article> </div> </section> <section class="sample sample-scrollToTop"> <div class="container"> <h2>Scroll to top</h2> <pre><code>window.scroll({ top: 0, left: 0, behavior: 'smooth' });</code></pre> <p><strong>or</strong></p> <pre><code>document.querySelector('header').scrollIntoView({ behavior: 'smooth' });</code></pre> <div class="actions"> <button class="btn js-scroll-to-top">scroll to top</button> </div> </div> </section> <section> <div class="container"></div> </section> <section class="featured"> <div class="container"> <a class="featured__link" href="https://github.com/iamdustan/smoothscroll">Polyfill on <strong>GitHub</strong></a> <a class="featured__link" href="https://github.com/iamdustan/smoothscroll-polyfill">Polyfill on <strong>npm</strong></a> <a class="featured__link" href="https://drafts.csswg.org/cssom-view/#extensions-to-the-window-interface">Draft on <strong>W3C</strong></a> <a class="featured__link" href="https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-behavior">Documentation on <strong>MDN</strong></a> </div> </section> <footer> <div class="container"> <p>Polyfill written by <a href="https://twitter.com/iamdustan">Dustan Kasten</a> and <a href="https://twitter.com/jeremenichelli">Jeremias Menichelli</a></p> <p>All rights reserved &copy; <a href="https://iamdustan.github.io/smoothscroll">https://iamdustan.github.io/smoothscroll</a></p> </div> </footer> <script> // add event listener on load window.addEventListener('load', function() { // scroll to bottom document.querySelector('.js-scroll-to-bottom').addEventListener('click', function(e) { e.preventDefault(); window.scrollTo({ top: document.body.clientHeight - window.innerHeight, left: 0, behavior: 'smooth' }); }); // scroll to top document.querySelector('.js-scroll-to-top').addEventListener('click', function(e) { e.preventDefault(); document.querySelector('header').scrollIntoView({ behavior: 'smooth' }); }); // scroll by document.querySelector('.js-scroll-by').addEventListener('click', function(e) { e.preventDefault(); window.scrollBy({ top: 100, left: 0, behavior: 'smooth' }); }); // scroll back document.querySelector('.js-scroll-back').addEventListener('click', function(e) { e.preventDefault(); window.scrollBy({ top: -100, left: 0, behavior: 'smooth' }); }); // scroll into view document.querySelector('.js-scroll-into-hello').addEventListener('click', function(e) { e.preventDefault(); document.querySelector('.hello').scrollIntoView({ behavior: 'smooth' }); }); }); </script> </body> </html>
DylanPiercey/smoothscroll
index.html
HTML
mit
10,145
<?php namespace spec\Welp\MailchimpBundle\Event; use PhpSpec\ObjectBehavior; use Prophecy\Argument; class WebhookEventSpec extends ObjectBehavior { function let($data = ['test' => 0, 'data' => 154158]) { $this->beConstructedWith($data); } function it_is_initializable() { $this->shouldHaveType('Welp\MailchimpBundle\Event\WebhookEvent'); $this->shouldHaveType('Symfony\Component\EventDispatcher\Event'); } function it_has_data($data) { $this->getData()->shouldReturn($data); } }
welpdev/mailchimp-bundle
spec/Event/WebhookEventSpec.php
PHP
mit
552
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) require 'bundler/setup' # Set up gems listed in the Gemfile. require 'rubygems' require 'rails/commands/server' =begin module Rails class Server alias :default_options_bk :default_options def default_options default_options_bk.merge!(Host: '120.27.94.221') end end end =end
xiaominghe2014/AccountsSys
config/boot.rb
Ruby
mit
365
<!DOCTYPE html> <html lang="en"> <head> <?php include "htmlheader.php" ?> <title>The War of 1812</title> </head> <body> <?php include "pageheader.php"; ?> <!-- Page Header --> <!-- Set your background image for this header on the line below. --> <header class="intro-header" style="background-image: url('img/1812ships.jpg')"> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"> <div class="post-heading"> <h1>The Second American War for Independence</h1> <h2 class="subheading">And what caused it</h2> <span class="meta">Content created by Wat Adair and Scotty Fulgham</span> </div> </div> </div> </div> </header> <!-- Post Content --> <article> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"> <p>At the outset of the 19th century, Great Britain was locked in a long and bitter conflict with Napoleon Bonaparte’s France. In an attempt to cut off supplies from reaching the enemy, both sides attempted to block the United States from trading with the other. In 1807, Britain passed the Orders in Council, which required neutral countries to obtain a license from its authorities before trading with France or French colonies.</p> <p>The Royal Navy also outraged Americans by its practice of impressment, or removing seamen from U.S. merchant vessels and forcing them to serve on behalf of the British. In 1809, the U.S. Congress repealed Thomas Jefferson’s unpopular Embargo Act, which by restricting trade had hurt Americans more than either Britain or France. Its replacement, the Non-Intercourse Act, specifically prohibited trade with Britain and France. It also proved ineffective, and in turn was replaced with a May 1810 bill stating that if either power dropped trade restrictions against the United States, Congress would in turn resume non-intercourse with the opposing power</p> <h2 class="section-heading">Causes of the War</h2> <p>In the War of 1812, the United States took on the greatest naval power in the world, Great Britain, in a conflict that would have an immense impact on the young country’s future. Causes of the war included British attempts to restrict U.S. trade, the Royal Navy’s impressment of American seamen and America’s desire to expand its territory.</p> <h2 class="section-heading">Effects of the War</h2> <p>The war of 1812 was thought of as a relatively minor war but it had some lasting results, It is thought of as a decisive turning point in canadians and native americans losing efforts to govern themselves. The war also put an end to the federalist party. The party had been accused of being unpatriotic because they were against war. Some people think the most important effect of the war was the confidence that it gave america.</p> <blockquote> "The war has renewed and reinstated the national feelings and character which the Revolution had given, and which were daily lessened. The people . . . . are more American; they feel and act more as a nation; and I hope the permanency of the Union is thereby better secured." - First Lady Dolley Madison, 24 August 1814, writing to her sister as the British attacked Washington, D.C. </blockquote> <p><i>Page content written by Wat Adair and Scotty Fulgham.</i></p> </div> </div> </div> </article> <hr> <?php include "pagefooter.php"; ?> </body> </html>
roll11tide/europeanwar
1812.html.php
PHP
mit
3,908
CardFlip ======== FlipContainerView is a class which allows users to set a front and a back view of a 'card', and flip it over to display a detail view. It supports panning, so the user can 'play' with the card, pulling it down gradually or by swiping it quickly. If the user is panning, the card will automatically flip once it gets to a specific point to prevent the user from rotating it 90 degrees, which would hide the card completely for a brief period (since we're rotating two dimensional views with no depth). This code was originally going to be used in a commercial project but was removed when we decided to use a different user experience flow. I thought this code was interesting enough to publish it in its own right. [![Demo](http://img.youtube.com/vi/uUrqgbIefd4/0.jpg)](http://www.youtube.com/watch?v=uUrqgbIefd4) FlipContainerView class ----------------------- This class is the interesting part and contains references to two <code>UIViews</code>, <code>frontView</code> and <code>backView</code>. Set these to whatever you like; they should be the same size as each other. <code>frontView</code> is, surprise, the front of the card. Here, it's intended that you display a view which has contains a summary, or a small amount of information. <code>backView</code> is the back of the card. Because this will be upside down when the view is flipped, you probably shouldn't put anything useful here. A background color is probably best. FlipContainerDelegate --------------------- Your view controller should implement this delegate. Don't forget to hook it up to <code>FlipContainerView</code>. The delegate provides the following methods: - <code>showFront</code> - <code>showBack</code> - <code>didShowFront</code> - <code>didShowBack</code> If you look at the provided sample project, you'll see that another view, <code>DetailView</code> is shown on screen once the card flips to the back. This is a bit of a 'fake' view, since it's meant to represent the real reverse side of the card. However, <code>FlipContainerView</code>'s <code>backView</code> will be upside down and stretched out once a flip occurs. You should, again, hook up your view controller to this <code>DetailView</code> via a delegate and call <code>flipToFront</code> when you want to close it. FAQs ==== **Does this require any frameworks?** Just <code>QuartzCore</code>. Be sure to include it under the "Link Binary with Libraries" section in your project's Build Phases. **Why does <code>DetailView</code> even exist? Why can't you use <code>backView</code>?** Because <code>backView</code> will be upside down when you flip the card over, and I wanted <code>DetailView</code> to take up the size of the screen. In the original purpose the code was written for, it was more than sufficient that I blow out <code>backView</code> to a big size to fill out the entirety of the screen and sneakily do an <code>addSubview</code> of the real view. Your purpose may be different, and you're more than free to make it do whatever you like with the code. **What sort of things can I put on each of the card views?** Anything you want. They're <code>UIView</code>s after all. **One big card isn't very useful!** Of course, you're free to put as many of these things on screen as you wish and make them as large as you like. It was actually designed to be a view inside Nick Lockwood's amazing [iCarousel](https://github.com/nicklockwood/iCarousel). **What iOS versions do I need?** I tested this on iOS 5 and 6. It should theoretically work on anything that uses ARC (iOS 4.3+) **Why does this require ARC?** Because I wrote this in 2013. **This isn't very customisable.** That'd be because originally this was developed to be part of a commercial project for one very specific purpose. You can tweak it however you like (eg, sensitivity, flip direction, etc) but there are currently no built-in options for that sort of thing. Licence ======= This project is licenced under the MIT Licence. You may use and change as you wish. No attribution is required. Developed by Jarrod Robins 2013.
jarrodrobins/CardFlip
README.md
Markdown
mit
4,113
body { font-family: Helvetica; color: #111; overflow: hidden; margin: 0; background: #f2f2f2; line-height: 1.5; } header { display: block; margin: 20% auto; text-align: center; font-size: 50px; font-weight: bold; } header span { position: relative; display: inline-block; } button { display: block; margin: 5px auto; padding: 5px; font-size: 15px; }
TheHagueUniversity/2017_1.1_programming-extended-course
wk4exercises/wk4exercise07/styles/mystyle.css
CSS
mit
398
/* * This file is part of SpongeAPI, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.api.data.types; import org.spongepowered.api.CatalogType; import org.spongepowered.api.util.annotation.CatalogedBy; /** * Represents a type of instrument. */ @CatalogedBy(InstrumentTypes.class) public interface InstrumentType extends CatalogType { }
frogocomics/SpongeAPI
src/main/java/org/spongepowered/api/data/types/InstrumentType.java
Java
mit
1,532
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" /> <title>EMAT20005</title> </head> <body> <h1>EMAT20005: Product Realisation<br /> Personal Rapid Transit </h1> <p> Fall 2010, Weeks 6-10<br/> 11:00-13:00 on Wednesdays in QB 1.59<br/> Instructor: <a href="..">John Lees-Miller</a> </p> <h2>News</h2> <h3>8 Dec, 2010</h3> <ul> <li>To submit the <a href="#report">final report</a>: either upload the document and supporting sim files to <a href="http://www.bristol.ac.uk/fluff/">fluff</a> and <a href="http://www.enm.bris.ac.uk/scripts/contact/contact.php?id=aVubjyT9x14fDkHBxcR3DiU1UasS4F">send</a> me the link, or drop them in the appropriate box in the Queen's School Office.</li> </ul> <h3>2 Dec, 2010</h3> <ul> <li>Some additional help on gravity models is available <a href="more_notes_on_gravity_models.pdf">here</a>.</li> <li>Clarification: hand-drawn sketches are fine for task 4.</li> </ul> <h3>26 Nov, 2010</h3> <ul> <li>More details for the <a href="#presentation">presentation</a> and <a href="#report">final report</a> have been added.</li> <li>The page limit for the individual report has increased from 5 pages to 6, in order to allow two pages for each of the three iterations.</li> </ul> <h2>Outline</h2> <ul> <li>Week 6 (first class Wednesday, 17 Nov) <ul> <li>lecture: introduction to PRT + advice on choosing a site (<a href="https://www.bris.ac.uk/fluff/u/enjdlm/XvZ36tC1XtwJC3jbT4w5HwKE/">slides</a>)</li> <li>form groups</li> <li>set up <a href="#sim">ATS/CityMobil design and simulation tool</a></li> <li>choose a site</li> <li>start on demand estimates</li> </ul></li> <li>Week 7 <ul> <li>lecture: simulator demo, gravity models (<a href="https://www.bris.ac.uk/fluff/u/enjdlm/ZM5CBvsbnZCDtsYYt3e0CQKE/">slides</a>), performance metrics</li> <li>work on <a href="#demand">task 2</a> and <a href="#design">task 3a</a></li> <li><strong>Deliverable:</strong> in class, show me <ul> <li>a map of your site,</li> <li>the scale of the map, in meters per pixel, and</li> <li>the major demand generators in the area.</li> </ul></li> </ul></li> <li>Week 8 <ul> <li>questions and answers</li> <li>work on <a href="#design">task 3b/3c</a></li> <li><strong>Deliverable:</strong> at the start of class, show me a simulation file containing your group's preliminary network (<a href="#design">task 3a</a>), including stations and network.</li> </ul></li> <li>Week 9 <ul> <li>questions and answers</li> <li>work on <a href="#design">task 3c</a> and <a href="#design-stations">task 4</a></li> </ul></li> <li>Week 10 <ul> <li><strong>Deliverable:</strong> 10 minute <a href="#presentation">presentation</a> in class</li> <li><strong>Deliverable:</strong> <a href="#report">final report</a> due at 4pm on Friday, 17 December</li> </ul></li> </ul> <h2>Assessment</h2> <table border="1" cellpadding="4"> <tr><th>Item</th><th>Weight</th></tr> <tr><td>deliverable in week 7</td><td>5%</td></tr> <tr><td>deliverable in week 8</td><td>5%</td></tr> <tr><td>final presentation</td><td>30%</td></tr> <tr><td>final report: group component</td><td>40%</td></tr> <tr><td>final report: individual component</td><td>20%</td></tr> </table> <a name="sim"></a> <h2>Task 0 &nbsp; Get the simulation tool.</h2> <h3>For the Lab Machines</h3> <ol> <li>Download <a href="atscitymobil-20101123.zip">atscitymobil-20101123.zip</a> (2.5MB). (Right click and choose Save Target As...)</li> <li>Extract the zip file to your university drive.</li> <li>Double click <em>atscitymobil.exe</em> to launch.</li> </ol> <h3>For your Laptop / PC</h3> <p> Please use this <a href="http://www.ultraprt.com/uploads/citymobil/atscitymobil-bundled-setup-20101123.exe">installer</a> (20MB). You can use the zip file above on your home machine, but this installer sets up shortcuts and file associations. Note that the simulator only runs on Windows, at present. </p> <h3>Tutorial</h3> <p>This <a href="http://www.ultraprt.com/prt/implementation/simulation/">tutorial</a> is a good reference on how to use the simulator.</p> <a name="site"></a> <h2>Task 1 &nbsp; Choose a site.</h2> <p>You will need a map of the area, and you will have to know the scale of the map image, in meters per pixel. (Hint: A screenshot from <a href="http://www.google.com/earth">Google Earth</a> or <a href="http://maps.google.co.uk/">Google Maps</a> is good, and Google Earth has a tool for measuring distances.)</p> <p>You will need to identify the major demand generators in the area. (Hint: Google Earth and Google Maps label most major facilities and land marks.)</p> <p>Your site can be anywhere, but keep in mind that you have to estimate what the potential passenger demand will be. For ideas, you can go to <a href="http://www.ultraprt.com/applications">http://www.ultraprt.com/applications</a> but please do <em>not</em> use a site that has already been studied by someone else.</p> <p>Alternatively, you can work from a <a href="http://en.wikipedia.org/wiki/Greenfield_land">greenfield</a> (undeveloped) site, and develop your site around your PRT system, rather than trying to fit the system into an existing site. Keep in mind, however, that designing both the site and the PRT system will require more work. If your group wants to do this, please discuss with me before the end of week 6.</p> <p>Also note that your service area must not exceed 5km by 5km, due to limitations of the simulator.</p> <a name="site-outputs"></a> <h3>Outputs</h3> <ul> <li>A map of your site.</li> <li>The scale of the map, in meters per pixel.</li> <li>A list of the major demand generators in the area.</li> </ul> <a name="demand"></a> <h2>Task 2 &nbsp; Place stations and create demand scenarios.</h2> <p>Now you are ready to place stations near your site's demand generators. Exactly how many stations you place and where you place them depends on your estimates for the demand between pairs of stations. For this project, you will have to make several (educated) guesses at what the demand will be.</p> <p>When deciding where to place stations, you should be thinking about the following guidelines.</p> <ul> <li>Passengers will typically walk to or from the PRT stations. A good rule of thumb is that walking distances from each station to any nearby demand generators should be less than about 400m, because very few people will be willing to walk farther than this.</li> <li>You can build stations inside or on top of existing buildings, or you can build free-standing stations.</li> <li>To get an idea of the area required for a station, see these <a href="http://www.ultraprt.com/Bath/home-2/competition-details/stations/">design guidelines</a>. However, do not spend too much time worrying about all of the details; you will do some detailed design work, later.</li> <li>You must be able to access the stations with guideways.</li> <li>Stations cost money.</li> <li>The maximum number of stations is 20, due to simulator limitations.</li> <li>The minimum number of stations is 12.</li> <li>The total flow of vehicles (in flow plus out flow) at any station must not exceed 300 vehicles per hour. If you have a large demand generator, you should split the demand between several stations.</li> </ul> <p>To represent the passenger demand, you will create one <em>demand scenario</em> per group member. Each scenario describes the passenger demand at a particular time. For example, a large urban system might have an <em>AM peak</em> during morning rush hour, in which most of the demand is from the outskirts to the center. The evening rush hour is the <em>PM peak</em> demand. Outside of peak times, the passenger flows are typically smaller and more <em>balanced</em>; that is, the average flow into each region tends to equal the average flow out. Other scenarios might come from special events, for example at a stadium or convention centre. Each scenario will suggest different system optimisations.</p> <p>The data required to define a scenario are the in flow and out flow of vehicles at every station. As mentioned above, the total flow (in plus out) for each station must be less than 300 vehicles per hour. Also, the <em>sum</em> of all the in flows must equal the sum of all the out flows for each scenario; these sums are written <em>T<sub>i</sub></em> in the table below. Your scenarios must include one <em>balanced flow</em> scenario, in which the flow in and out of each station is (roughly) equal. The others should represent peaks with different spatial distribution and intensity. The total flow (<em>T<sub>i</sub></em>) for the whole system must be at least 700 vehicle trips per hour for the balanced scenario and at least 1300 trips per hour for the peak scenarios.</p> <p>Note that the simulator needs to know the demand in vehicles per hour; the average <em>vehicle occupancy</em> relates this to passengers per hour. To help calibrate your numbers, a reasonable guess at vehicle occupancy is 1.2 passengers per vehicle, but it will be higher for some sites, for example if there are many couples or families using the system. Different scenarios may also have different vehicle occupancies.</p> <p>Finally, for each scenario you will have to estimate how many hours per day (or per week) each scenario will occur. We will assume here that the actual demand will always be like one of the scenarios. This allows us to estimate the system's annual patronage, which will be important in subsequent sections.</p> <p>You may want to organize these data in a table like the following (it would be a good idea to use a spreadsheet).</p> <a name="scenario-table"></a> <table border="1" cellpadding="4"> <tr><th></th> <th colspan="6">Vehicle Flows (vehicles/hour)</th> </tr> <tr><th align="right">Scenario:</th> <th colspan="2">Balanced</th> <th colspan="2">AM Peak</th> <th colspan="2">PM Peak</th> </tr> <tr><th align="left">Station</th> <th>In</th><th>Out</th> <th>In</th><th>Out</th> <th>In</th><th>Out</th> </tr> <tr><td>Park Plaza East</td> <td align="right">80</td><td align="right">80</td> <td align="right">50</td><td align="right">250</td> <td align="right">200</td><td align="right">80</td> </tr> <tr><td>Park Plaza West</td> <td align="right">80</td><td align="right">80</td> <td align="right">50</td><td align="right">150</td> <td align="right">200</td><td align="right">30</td> </tr> <tr><td>...</td> <td align="right">...</td><td align="right">...</td> <td align="right">...</td><td align="right">...</td> <td align="right">...</td><td align="right">...</td> </tr> <tr><th align="left">Total In/Out</th> <td align="center">T<sub>1</sub></td> <td align="center">T<sub>1</sub></td> <td align="center">T<sub>2</sub></td> <td align="center">T<sub>2</sub></td> <td align="center">T<sub>3</sub></td> <td align="center">T<sub>3</sub></td> </tr> <tr><th align="left">Total Hourly Flow</th> <td align="center" colspan="2">T<sub>1</sub></td> <td align="center" colspan="2">T<sub>2</sub></td> <td align="center" colspan="2">T<sub>3</sub></td> </tr> <tr><td colspan="7">&nbsp;</td></tr> <tr><th align="left">Hours / Day</th> <td align="center" colspan="2">...</td> <td align="center" colspan="2">...</td> <td align="center" colspan="2">...</td> </tr> <tr><th align="left">Total Daily Vehicle Flow</th> <td align="center" colspan="6">...</td> </tr> <tr><th align="left">Vehicle Occupancy</th> <td align="center" colspan="6">1.2 passengers / vehicle</td> </tr> <tr><th align="left">Total Passengers / Day</th> <td align="center" colspan="6">...</td> </tr> <tr><th align="left">Total Passengers / Year</th> <td align="center" colspan="6">...</td> </tr> </table> <p>The next step is to run a <a href="http://en.wikipedia.org/wiki/Trip_distribution#Gravity_model">gravity model</a> to turn each scenario into an <em>origin-destination demand matrix</em> (OD matrix) that you can use with the simulator. The OD matrix specifies the average number of vehicle trips per hour between each pair of stations. The simulator uses this matrix to to generate passengers randomly according to a <a href="http://en.wikipedia.org/wiki/Poisson_process">Poisson process</a>.</p> <p>The equations for the gravity model and an algorithm for running it will be described in class. Use the straight-line distances between stations as "costs." (<strong>Note</strong>: the version of the sim that you downloaded in the first week did not report straight-line distances in the output; the <a href="#sim">latest version</a> does.) The suggested dispersion factor is 0.5. You are free to tweak this factor, or to edit the resulting OD matrix directly, if you wish, provided that the resulting matrix still satisfies the constraints on total flow at stations and for the system as a whole. You can implement the algorithm however you like; it's possible to do it in MATLAB or in Excel (hint: use the <a href="enable_excel_2007_solver.pdf">solver add-in</a>).</p> <h3>Outputs</h3> <ul> <li>An ATS/CityMobil simulator (.atscm) file with <ul> <li>your map as the background image,</li> <li>the background image scale (meters per pixel) set properly, and</li> <li>your stations in the simulator (place them with the Build tool).</li> </ul></li> <li>One scenario per group member.</li> <li>One origin-destination demand matrix per scenario.</li> <li>See also section 1 of the <a href="#report">final report</a>.</li> </ul> <a name="design"></a> <h2>Task 3&nbsp; Design a PRT network.</h2> <p>Now you are ready to connect the stations with guideways. We'll do this in three stages.</p> <ol type="a"> <li>As a group, create a preliminary network design based on the given guidelines (below). Here you should just aim to connect all the stations and add one depot, in order to get the simulation running.</li> <li>Individually, pick a demand scenario and optimise the network for that scenario using the given cost structure.</li> <li>As a group, agree on a final design that takes all of the scenarios into account.</li> </ol> <p>For (a), you will have to show me the simulation in class in week 8. For (b), each group member must write an appendix to the final report that documents the optimisation process for his/her scenario.</p> <h3>Guidelines</h3> <ul> <li>The vehicles can only run on dedicated guideway. Pedestrians and road traffic cannot mix with moving PRT vehicles. The usual way to accommodate this is to build elevated guideway, but you can also run at-grade (on the ground, protected by a fence), or below-grade (in a tunnel). At-grade guideway is much less expensive than elevated guideway (see below). (Note that the simulator does not distinguish between grades.)</li> <li>A good network design strategy is to connect the stations in one-way loops, like in the Urban Case Study network that comes bundled with the simulator.</li> <li>However, your loops should not be too long, because travel times for trips that go the long way around the loop become too large. For example, in the Urban Case Study, the trip time from station 8 to station 7 is only about 40s, but the travel time from 7 to 8 (the long way around) is nearly 8 minutes.</li> <li>Whether a long travel time between a pair of stations is acceptable depends on how much demand you expect between those stations. You may choose to build extra guideway to make some loops shorter or connect loops more directly, or you may choose to reverse the direction of a loop. Note that this depends on the scenario.</li> <li>Your guideways should follow existing rights of way (roads, alleys, railway lines, bridges) where possible. You can cut through buildings, especially if it allows you to put a station inside.</li> <li>Guideway costs money. However, you must connect all of the stations, and building extra guideway for more direct routes reduces travel times and the number of vehicles that you need.</li> <li>To reduce passenger waiting times at a station, you can construct a depot upstream of the station. Depots help the system's empty vehicle management algorithm to keep vehicles close to where they will be needed.</li> <li>See these <a href="http://www.ultraprt.com/Bath/home-2/competition-details/guideway/">design guidelines</a> for more information on the guideways. However, do not spend too much time worrying about all of the details; you will do some detailed design work for some small sections, later.</li> </ul> <h3>Cost Structure for Optimisation</h3> <p>Your objective is to minimize the sum of system costs and user costs, according to the following cost estimates.</p> <a name="costs"></a> <table border="1" cellpadding="4"> <tr><th>Capital Costs</th><th>&pound;</th></tr> <tr><td>1 vehicle</td><td align="right">50k</td></tr> <tr><td>1 station</td><td align="right">0.5M</td></tr> <tr><td>1 depot</td><td align="right">0.4M</td></tr> <tr><td>1 km at-grade guideway</td><td align="right">1M</td></tr> <tr><td>1 km elevated guideway</td><td align="right">2.5M</td></tr> <tr><td>other</td><td align="right">+50%</td></tr> <tr><th>Operating Costs</th><th>&pound;</th></tr> <tr><td>1 passenger km</td><td align="right">0.15</td></tr> <tr><th>User Costs</th><th>&pound;</th></tr> <tr><td>1 minute passenger travel time</td><td align="right">0.1</td></tr> <tr><td>1 minute passenger waiting time</td><td align="right">0.2</td></tr> </table> <p>Some of the costing inputs you can read directly from the network, but the number of vehicles and the mean passenger waiting time must be estimated by simulation. You should run 5 simulations and average the results, in order to get reliable numbers.</p> <p>The simulator output includes the total track length, but the simulator does not know anything about grades. For costing, you should estimate roughly what percentage of your track is at-grade. Do not worry about getting this exactly right, because all of the costs are rough; just try to estimate to within 10% or so.</p> <p>Once you have computed the base capital costs (vehicles, stations, depots and guideway), add 50% to cover related expenses, such as central control software and hardware, and a contingency.</p> <p>The system operating costs are given as a rough total cost per passenger kilometer. The simulator output includes the 'mean demand-weighted passenger trip distance,' which you can use to compute the operating cost per passenger trip. To scale this up to an annual operating cost, you will use the passenger trips / year figure from task 2. (Note that when you are optimising for a single scenario, multiplication by the total passengers per year effectively assumes that the demand is <em>always</em> like this scenario; this is not really true, but it is good enough for our purposes here.)</p> <p>You can approach the user costs similarly; here the relevant simulator outputs are the 'mean demand-weighted passenger trip time' and the mean passenger waiting time. The user costs are based on a standard <a href="http://en.wikipedia.org/wiki/Value_of_time">value of time</a> calculation.</p> <p>These costs are rough estimates. The main point is that there are trade-offs between capital costs, operating costs and user costs. For example, you can build more guideway to reduce travel times, which increases your capital cost but decreases your operating and user costs.</p> <p>Operating and user costs occur over time, so you should use <a href="http://en.wikipedia.org/wiki/Net_present_value">present values</a> to weigh them against capital costs. Assume the standard public works discount rate of 6% per year, and discount over 30 years.</p> <p>These costs give you a way of evaluating networks objectively. However, you should be mindful of externalities. For example, this does not include a cost for visual intrusion in culturally sensitive areas. It also does not account for changes in pedestrian flows; areas that were once quiet could become busy, and vice versa. You may reject a design that is "optimal" by cost but undesirable for other reasons.</p> <p>I strongly recommend that you create a spreadsheet to keep track of the cost calculations.</p> <h3>Constraints</h3> <ul> <li>Maximum number of depots is 5.</li> <li>90% of passengers should wait less than 60s (but somewhat longer tails are fine for peak demand scenarios).</li> <li>You may add new stations or remove stations that have low value for some or all scenarios (e.g. low demand and/or requiring a lot of extra infrastructure). However, you will then have to modify the scenarios and regenerate demand matrices. The total demand must stay within the limits given in task 2.</li> </ul> <a name="design-composite"></a> <h3>Optimising for Multiple Scenarios</h3> <p>Once each member of your group has optimised your initial network for one scenario, you will apply what you've learned to design a network that works for all of them.</p> <p>To evaluate your final network, use a <em>composite cost</em> that describes its combined performance on all of the demand scenarios. The capital costs apply to all scenarios equally, but the operating and user costs depend on the demand. So, you should evaluate your final network on each scenario and record the trip distance, trip time and passenger waiting time for each one. Then you should weight these by how frequently each scenario occurs (as estimated in task 2) and apply the cost model. (Also note that the number of vehicles you need is the largest number needed in any single scenario.)</p> <p>You should do several iterations to improve the composite cost. Again, be mindful of externalities.</p> <p>Note: The simulator will only let you enter one OD matrix at a time, but you can copy and paste OD matrices to/from the sim. The best way to do this is to copy the matrix from one simulation into Excel, delete the last row and the last column (the totals), and then paste it into another simulation.</p> <h3>Cost/Benefit Analysis</h3> <p>To measure the user benefits that could come from building a PRT system, one must compare user costs with PRT to user costs with existing modes. Here we will compare PRT with a very simplistic model of a bus system. Assume that users wait an average of 5 minutes for the bus, and that the average travel time by bus is the time taken to travel the <em>straight-line distance</em> from origin to destination at 12km/h. (<strong>Note</strong>: the version of the sim that you downloaded in the first week did not report straight-line distances in the output; the <a href="#sim">latest version</a> does.) Use the travel and waiting time savings (or not) with the <a href="#costs">cost table</a> to compute user benefits and system costs.</p> <h3>Outputs</h3> <p>See section 2 in the <a href="#report">final report</a>.</p> <a name="design-stations"></a> <h2>4 &nbsp; Design two stations in detail.</h2> <p>Pick two stations that are interesting or challenging, for example due to large size or passenger volumes, culturally sensitive surroundings or an architecturally interesting setting (e.g. integrated into a building), and produce a conceptual design for each one.</p> <p>You should produce a plan view of the station, keeping the following questions in mind.</p> <ul> <li>Precisely where will the station be built? Is it a standalone station, or is it part of an existing building? If it is standalone, is the station area on the ground, or is it elevated?</li> <li>How will you connect the guideways into and out of the station?</li> <li>How will passengers enter and exit the station?</li> <li>How many berths will the station have? (Hint: use the largest number of berths assigned by the simulation in any demand scenario.)</li> </ul> <p>The "vehicle side" of the station should be consistent with these <a href="http://www.ultraprt.com/Bath/home-2/competition-details/stations/">design guidelines</a>; see also <a href="http://www.ultraprt.com/prt/infra/station-design/">this overview</a>. The <a href="http://www.ultraprt.com/uploads/DesignContest/Station_Guide.skp">3D design template</a> (in SketchUp) is particularly helpful. You should consider where the main line and the on- and off-ramps will go. </p> <p>Note: hand-drawn sketches are fine.</p> <p><strong>Bonus</strong>: Construct an architectural rendering (e.g. in SketchUp) of the station. You can use the 3D design template in the guidelines to get started.</p> <h3>Outputs</h3> <p>See section 3 in the <a href="#report">final report</a>.</p> <a name="presentation"></a> <h2>Details for Presentation</h2> <p>Each group's presentation will last around 10 minutes with a few minutes for questions. Your presentation should cover essentially the same content as the main body of the <a href="#report">final report</a> (sections 1-3), with a focus on the visual and qualitative aspects of your design. Every group member must participate in the presentation.</p> <a name="report"></a> <h2>Details for Final Report</h2> <p>Each group should submit a report as described below. The main body of the report (sections 1-3) is limited to 5000 words on 20 pages. In addition, each group member should submit an appendix (see below) of up to 600 words on 6 pages. Note that these are word and page <em>maxima</em>: you should aim to be concise (and use lots of pictures!).</p> <p>In addition to the written report, please submit the following ATS/CityMobil (.atscm) simulation files.</p> <ul> <li>An .atscm file for your group's final network.</li> <li>An .atscm file for each group member's final network, including the demand matrix for the corresponding demand scenario.</li> </ul> <p>To submit: either upload the document and supporting sim files to <a href="http://www.bristol.ac.uk/fluff/">fluff</a> and <a href="http://www.enm.bris.ac.uk/scripts/contact/contact.php?id=aVubjyT9x14fDkHBxcR3DiU1UasS4F">send</a> me the link, or drop them in the appropriate box in the Queen's School Office.</p> <h3>Marking Criteria</h3> <p>The report will be marked according to the following five equally weighted criteria.</p> <ul> <li>Clarity and Conciseness</li> <li>Problem Analysis</li> <li>Down-select Logic (comparison of iterations / alternatives)</li> <li>Technology Employed</li> <li>Overall Design and Solution</li> </ul> <h3>Final Report Content</h3> <h4>Section 1: Site, Stations and Demand</h4> <ul> <li>A map of your site with labels for the main demand generators.</li> <li>Where is your site?</li> <li>Why might a PRT system be appropriate for this site?</li> <li>Table of scenarios (one per group member) like <a href="#scenario-table">this one</a>.</li> <li>How did you guess the in and out flows for your scenarios?</li> <li>How did you implement the gravity model?</li> <li>What is the effect of the dispersion parameter?</li> <li>What dispersion parameter value(s) did you use?</li> </ul> <h4>Section 2: System Optimisation</h4> <ul> <li>A screenshot of your group's initial network (<a href="#design">task 3a</a>).</li> <li>A record of three iterations / design alternatives evaluated according to <a href="#design-composite">composite cost</a>, one of which should be selected as your group's "final" (preferred) network. For each alternative, include <ul> <li>a screen shot of the network,</li> <li>a table of costs (capital, operating, user, total and net present value), and</li> <li>a brief description of how it relates to other alternatives and/or the networks you designed for individual scenarios.</li> </ul> </li> <li>Cost/benefit analysis for the final network: <ul> <li>Explain your cost/benefit calculations.</li> <li>Do the benefits outweigh the costs?</li> <li>What are the most important variables (travel times, waiting times, discount factor, ...)? (sensitivity)</li> <li>Are there other benefits or costs (not included in the cost function here) that could change the conclusion?</li> </ul></li> </ul> <h4>Section 3: Detailed Design for Two Stations</h4> <p>For each of the two stations:</p> <ul> <li>Why is the station interesting and/or challenging? What other stations did you consider before selecting these two?</li> <li>How many berths does the station need?</li> <li>What are the effects of the station on its surrounding area, in terms of economic, environmental and social impact?</li> <li>Plan view of the station (see <a href="#design-stations">guidelines</a>).</li> <li><strong>Bonus:</strong> include architectural renderings of one or both stations (see <a href="#design-stations">guidelines</a>).</li> </ul> <h4>Appendices (one per group member)</h4> <p>Your appendix should describe the process that you (individually) went through to optimise the system for your scenario. In particular, you should provide a record of three iterations; for each one, you should include </p> <ul> <li>a screen shot of the network,</li> <li>a table of costs (capital, operating, user, total and net present value), and</li> <li>a brief description of what changes you made and your rationale.</li> </ul> <h2>Other Resources</h2> <ul> <li><a href="http://en.wikipedia.org/wiki/Personal Rapid Transit">Personal Rapid Transit</a> on Wikipedia</li> <li><a href="http://www.ultraprt.com">ULTra PRT</a> company site</li> <li>ULTra PRT <a href="http://www.ultraprt.com/bath">design competition for Bath</a></li> <li>Other PRT vendors: <a href="http://www.2getthere.eu/">2getthere</a>, <a href="http://www.vectusprt.com/">Vectus PRT</a> </li> </ul> <script type="text/javascript"> var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); </script> <script type="text/javascript"> try { var pageTracker = _gat._getTracker("UA-8962570-4"); pageTracker._trackPageview(); } catch(err) {}</script> </body> </html>
jdleesmiller/jdleesmiller.github.io
emat20005/index.html
HTML
mit
32,228
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Potlatch!</title> <link href="./static/css/skeleton.css" rel="stylesheet"> <link href="./static/css/style.css" rel="stylesheet"> </head> <body> <div id="potlatch"></div> <script src="./static/js/potlatch.js"></script> <script type="text/javascript"> var node = document.getElementById("potlatch"); var flags = { itemsUrl: "./items.json" }; Elm.Main.embed(node, flags); </script> </body> </html>
rafikdraoui/potlatch
index.html
HTML
mit
527
import React, { PropTypes } from 'react'; class Link extends React.Component { render() { return <article key={this.props.item.id} className="List-Item"> <header className="List-Item-Header"> <cite className="List-Item-Title"><a href={this.props.item.href}>{this.props.item.title}</a></cite> </header> <p className="List-Item-Description List-Item-Description--Short">{this.props.item.short_description}</p> </article> } } export default Link;
Shroder/essential-javascript-links
src/modules/List/components/Link/index.js
JavaScript
mit
484
# Udacity Software Debugging ## Introduction - Course: [**Udacity CS259 Software Debugging**](https://www.udacity.com/course/software-debugging--cs259) - Fee: **Free** - Approx. **1 ~ 2 Weeks** - Prerequisites - Python Experience - Review: **Excellent** - Content - [x] **Video + Script** - [x] **Quiz** - [x] **My Solutions** - [x] **Official Solutions** - **Syllabs** - Lesson 1: How Debuggers work - Lesson 2: Asserting Expectations - Lesson 3: Simplifying Failures - Lesson 4: Tracking Origins - Lesson 5: Reproducing Failures - Lesson 6: Learning from Mistakes - **What I Learned** - How to Manage Problems (Problem Life Cycle) - How to Analyse and Solve Problems ($\Phi$ Function, Delta Debugging) - How to Writer a Debugger in Python (Use `inspect` Object)
Quexint/Assignment-Driven-Learning
OCW/[Udacity]Software_Debugging/Readme.md
Markdown
mit
796
load File.expand_path("../target.rb", __FILE__) module ActiveRecord::Magic class Param::Server < Param::Target def default_options { online:nil, wildcard:false, autocomplete:true, current_server:false, current_channel:false, users:false, channels:false, servers:true, ambigious: false } end end end
gizmore/ricer4
lib/ricer4/core/params/server.rb
Ruby
mit
358
<!DOCTYPE html> <html lang="cs"> <head> <meta charset="utf-8"> <title>Cooland</title> <meta name="description" content=""> <meta name="author" content="Cooland"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="//fonts.googleapis.com/css?family=Merriweather:300,400,700&subset=latin,latin-ext" rel="stylesheet" type="text/css"> <link rel="icon" type="image/png" href="../img/favicon.png"> <link href="css/base.css" rel="stylesheet" type="text/css"> <link href="css/style.css" rel="stylesheet" type="text/css"> <link href="css/navmenu.css" rel="stylesheet" type="text/css"> <link href="css/gallery.css" rel="stylesheet" type="text/css"> </head> <body> <div id="header"> <div class="container main-nav"> <a href="/index" class="main-nav__logo"> <img src="img/cooland_logo.jpg" alt="Cooland"> </a> <nav class="fl"> <a href="" class="main-nav__burger js-nav"> <i class="icon-reorder"></i> </a> <div class="main-nav__block"> <div class="nav__left"> <a href="/o_nas" class=" ">O nás</a> <a href="/vize" class="">Vize</a> <a href="/nabizime" class="">Nabízíme</a> </div> <div class="nav__right"> <a href="/akce" class="">Akce</a> <a href="/media" class="">Média</a> <a href="/partaci" class="">Parťáci</a> </div> </div> </nav> </div> </div> <div id="main" class="container"> <h2>PARTNEŘI</h2> <h4>Domácí Květinářství</h4> <p>Květinářství, kde se pěstují, váží a prodávají kytice z českého venkova, pěstované pod širým nebem s láskou a péčí. </p> <p>Od roku 2016 je Domácí květinářství součástí iniciativy komunitou podporovaného zemědělství <a href="https://plus.google.com/u/0/communities/101783831094360976826" target="_blank">KPZ CooLAND</a>.</p> <p><a href="http://www.domacikvetinarstvi.cz" target="_blank">www.domacikvetinarstvi.cz</a></p> <h4>Ekumenická akademie</h4> <p>Akademie prosazuje alternativní přístupy při řešení současných světových ekonomických, sociálních a ekologických problémů a zároveň je přenáší do praxe v podobě konkrétních projektů.</p> <p>CooLAND je partnerem kampaně <a href="http://www.pestujplanetu.cz/" target="_blank">Pěstuj planetu</a> a dále spolupracuje s Ekumenickou akademií na realizaci společných akcí jako např. <a href="http://www.ekumakad.cz/cz/temata/ferova-letna" target="_blank">Férová Letná</a>.</p> <p><a href="http://www.ekumakad.cz/" target="_blank">http://www.ekumakad.cz/</a></p> <h4>Farma Lukava</h4> <p>Rodinná ekologická farma hospodařící v Jindřichovicích pod Smrkem a Dětřichovci, kde se zabývá především chovem dojných ovcí a zpracováním ovčího mléka. </p> <p>Od roku 2016 je farma součástí iniciativy komunitou podporovaného zemědělství <a href="https://plus.google.com/u/0/communities/101783831094360976826" target="_blank">KPZ CooLAND</a>.</p> <p><a href="http://www.lukava.net/" target="_blank">http://www.lukava.net/</a></p> <h4>Glopolis</h4> <p>Nezávislé analytické centrum (think-tank) se zaměřením na globální výzvy a příslušné odpovědi České republiky a EU.</p> <p>CooLAND se aktivně účastnil diskusí v rámci festivalu <a href="http://www.festivalalimenterre.cz/cz/" target="_blank">Země na talíři</a> a spolupracuje na šíření filmů v rámci ozvěn tohoto festivalu. Spolupracujeme na projektu <a href="http://glopolis.org/cs/projekty/menu-pro-zmenu/" target="_blank">Menu pro změnu</a>.</p> <p><a href="http://glopolis.org/cs/" target="_blank">http://glopolis.org/cs/</a></p> <h4>Harvest Films</h4> <p>Občanské sdružení hledá a nabízí divákům filmy, které dokáží zajímavým a srozumitelným způsobem uchopit, vysvětlit a prezentovat vědecká témata. </p> <p>CooLAND se podílel na přípravě a realizaci projektu <a href="http://www.ucimesefilmem.cz/" target="_blank">Učíme se filmem</a> a pravidelně se zapojuje do organizace <a href="http://lsff.cz/" target="_blank">Life Sciences Film Festivalu</a>.</p> <p><a href="http://www.harvestfilms.cz/" target="_blank">http://www.harvestfilms.cz/</a></p> <h4>Institut cirkulární ekonomiky</h4> <p>Nevládní organizace, která v podmínkách ČR usiluje o rozvoj cirkulární ekonomiky - konceptu založeného na vytváření funkčních vztahů mezi lidskou společností a přírodou.</p> <p>CooLAND se v roli moderátora účastní vybraných diskusí v rámci projektu <a href="http://incien.org/buzz-talks/" target="_blank">Buzz Talks</a>.</p> <p><a href="http://incien.org/" target="_blank">http://incien.org/</a></p> <h4>Kytky od potoka</h4> <p>Květinářství, kde vážou netradiční kytice z květin, které si sami pěstují nebo sbírají na loukách, v lesích nebo i na rumištích.</p> <p>CooLAND si kupuje kytky od potoka pro radost a potěšení a občas také holkám pomůžeme nějakou tu kytku zasadit.</p> <p><a href="http://www.kytkyodpotoka.cz/" target="_blank">http://www.kytkyodpotoka.cz/</a></p> <h4>Na ovoce</h4> <p>Na ovoce slouží jako komunitní platforma lidem, kteří chtějí zodpovědně využívat přírodní bohatství v podobě volně rostoucích ovocných stromů, keřů či bylinek. Iniciativa se rozhodla taková místa nejen mapovat, ale také přispívat k jejich udržitelnosti, zakládat nová a dbát na hodnoty, které rostliny pro člověka představují, tím přispívat ke zvýšení biodiverzity a udržení pozitiv kulturní krajiny, ve které člověk žije.</p> <p>CooLAND ve spolupráci s Na ovoce realizuje projekt Pražské sady a jejich popularizace</p> <p><a href="https://na-ovoce.cz/" target="_blank">https://na-ovoce.cz/</a></p> <h4>PRO-BIO LIGA</h4> <p>PRO-BIO liga je samostatnou spotřebitelskou pobočkou největšího českého spolku ekologických hospodářů – Svazu ekologických zemědělců PRO-BIO Šumperk. Posláním PRO-BIO ligy je informovat a chránit spotřebitele potravin, přispívat k celoživotnímu vzdělávání a zvyšovat všeobecnou ekogramotnost.</p> <p>CooLAND spolupracuje s PRO-BIO liga na realizaci přednášek a workshopů o ochraně zemědělské půdy.</p> <p><a href="http://www.biospotrebitel.cz" target="_blank">www.biospotrebitel.cz</a></p> <h4>Statek Karel Tachecí</h4> <p>Ekologický zemědělec hospodařící v Budyni nad Ohří, kde pěstuje zeleninu, obiloviny, mák a další rostliny bez použití chemie a umělých hnojiv.</p> <p>CooLAND s Karlem Tachecím spolupracuje od roku 2015 a je prvním zemědělcem, který se stal součástí iniciativy komunitou podporovaného zemědělství <a href="https://plus.google.com/u/0/communities/101783831094360976826" target="_blank">KPZ CooLAND</a>.</p> <p><a href="http://www.tacheci.cz/" target="_blank">http://www.tacheci.cz/</a></p> <h4>Kevin V. Ton</h4> <p>Kevin V. Ton patří mezi fotografy „uličníky“, tématem jeho fotografií je totiž především běžný život na ulici. Na jeho fotografiích se často objevují lidé, kteří žijí na okraji společnosti, mimo systém, a proto své fotografie Kevin chápe jako pouliční a sociální dokument. </p> <p>Kevin V. Ton svými fotografiemi pravidelně dokumentuje akce a setkání KPZ CooLAND. CooLAND ve spolupráci s PRO-BIO LIGA realizoval výstavu “Láska ke krajině prochází žaludkem” - fotografie Kevina Tona s příběhem první sezóny <a href="https://plus.google.com/u/0/communities/101783831094360976826" target="_blank">KPZ CooLAND</a>.</p> <p><a href="http://www.kevin-v-ton.com" target="_blank">http://www.kevin-v-ton.com</a></p> <h4>PRO - BIO s r.o.</h4> <p>PRO-BIO, obchodní společnost s r. o. je první český výrobce a významný dodavatel širokého sortimentu kvalitních biopotravin. Podporuje a rozvíjí ekologické zemědělství, svou činností přispívá k zachování zdravé planety. Vrací zapomenuté tradiční plodiny a potraviny do života lidí.</p> <p>CooLAND spolupracuje s PRO - BIO na výzkumu vlivu ekologického hospodaření na krajinu.</p> <p><a href="http://www.probio.cz" target="_blank">www.probio.cz</a></p> <h4>Pozemkový úřad Nymburk</h4> <p>Pozemkové úřady mají mimo jiné na starosti realizaci pozemkových úprav. Ty jsou jedním z nejefektivnějších nástrojů, jak pomoci zemědělské krajině k tomu, aby byla zdravá a zároveň v ní mohli hospodařit zodpovědní zemědělci.</p> <p>CooLAND s Pozemkovým úřadem Nymburk spolupracuje při osvětě v oblasti pozemkových úprav a pořádá exkurze na realizovaná opatření v krajině.</p> <p><a href="http://www.spucr.cz/" target="_blank">http://www.spucr.cz/</a></p> <h2>KOALICE A SÍTĚ</h2> <h4>Asociace místních potravinových iniciativ AMPI</h4> <p>Poslání Asociace místních potravinových iniciativ (AMPI) je podporovat blízký vztah lidí ke krajině, ve které žijí, a to prostřednictvím rozvoje místních potravinových systémů (komunitou podporovaného zemědělství, komunitních zahrad aj.) v České republice, které zde zastřešuje. </p> <p>CooLAND se jako člen AMPI podílí na organizaci akcí, realizaci projektů, spoluprací se zahraničními partnery a šíření myšlenky komunitou podporovaného zemědělství u nás. Jsme společnými koordinátory projektu Erasmus + Projekty mobility osob / Vzdělávání dospělých s názvem: Learning toward Access to Land.</p> <p><a href="http://asociaceampi.cz" target="_blank">http://asociaceampi.cz</a></p> <h4>Iniciativa potravinové suverenity</h4> <p>Iniciativa vznikla v roce 2015 jako diskusní platforma jednotlivců i organizací a klade si za cíl prosazovat potravinovou suverenitu jako politický koncept přístupu k zemědělství a potravinářství v ČR i v Evropě, propojovat aktéry v ČR, napomáhat vzniku a rozvoji aktivit podporující potravinovou suverenitu a fungovat jako spojka na podobné iniciativy v dzahraničí.</p> <p>CooLAND je jedním ze zakládajících členů iniciativy a v roce 2015 jsme byli spolupořadatelem prvního <a href="https://potravinovasuverenita.cz/akce/forum-potravinove-suverenity/" target="_blank">Fóra potravinové suverenity v ČR</a>.</p> <p><a href="https://potravinovasuverenita.cz/" target="_blank">https://potravinovasuverenita.cz/</a></p> <h4>Českomoravská komora pozemkových úprav</h4> <p>Českomoravská komora pro pozemkové úpravy (ČMKPÚ) byla založena již v r. 1990, jako zájmové sdružení pracovníků v oboru pozemkových úprav. Sdružuje projektanty, pracovníky státní správy – pozemkových a dalších úřadů, pracovníky výzkumných ústavů a vysokých škol, pracovníky dodavatelských stavebních organizací i další zájemce. Od svého vzniku spolupracovala a stále spolupracuje na tvorbě a novelizaci zákonů, vyhlášek, vládních nařízení, metodik, norem a dalších směrnic, souvisejících s oborem pozemkových úprav.</p> <p>CooLAND spolupracuje s ČMKPÚ popularizací tématu pozemkových úprav pořádáním exkurzí a psaním popularizačních článků, jelikož pozemkové úpravy jsou jedním z efektivních nástrojů pro ochranu zemědělské půdy.</p> <p><a href="http://www.cmkpu.cz/cmkpu/" target="_blank">http://www.cmkpu.cz/cmkpu/</a></p> <h4>URGENCI</h4> <p>URGENCI je mezinárodní síť pro rozvoj komunitou podporovaného zemědělství, která sdružuje jednotlivé občany, malé farmáře, spotřebitele i aktivisty a politiky, jejichž cílem je utváření solidárního partnerství mezi producentem a spotřebitelem potravin.</p> <p>CooLAND je součástí sítě od roku 2015. Jsme součástí <a href="http://urgenci.net/csa-research-group-people/" target="_blank">CSA Research Group</a>, jejímž výstupem je například publikace o stavu evropských KPZ: <a href="http://urgenci.net/wp-content/uploads/2016/05/Overview-of-Community-Supported-Agriculture-in-Europe-F.pdf" target="_blank">Overview of Community Supported Agriculture in Europe</a>.</p> <p><a href="http://urgenci.net/" target="_blank">http://urgenci.net/</a></p> <h4>Česká společnost ornitologická</h4> <p>Česká společnost ornitologická je dobrovolým spolkem profesionálů i amatérů, zabývajících se výzkumem a ochranou ptáků, zájemců o pozorování ptáků a milovníků přírody.</p> <p>CooLAND se zabývá ochranou ptáků žijících v zemědělské krajině podporou šetrného hospodaření. Zároveň využíváme metodiky ČSO pro výzkum ptačích populací jako indikátoru správného hospodaření zemědělských subjektů. </p> <p><a href="http://www.cso.cz" target="_blank">www.cso.cz</a></p> <h2>PODPORUJÍ NÁS</h2> <h4>Člověk v tísni</h4> <p>Nevládní nezisková organizace vycházející z myšlenek humanismu, svobody, rovnosti a solidarity, usilující o otevřenou, informovanou, angažovanou a zodpovědnou společnost k problémům doma i za hranicemi naší země.</p> <p>V roce 2016 nám Člověk v tísni umožnil uspořádat v prostorách svého centra Langhans výstavu fotografií <a href="https://www.clovekvtisni.cz/cs/kalendar/vystava-fotografii-laska-ke-krajine-prochazi-zaludkem" target="_blank">“Láska ke krajině prochází žaludkem”</a>.</p> <p>V roce 2015 jsem podávali grant Ministerstva průmyslu a obchodu na rozvoj ekologického zemědělství v Gruzii, kde byla místní mise Člověka v tísni lokálním partnerem.</p> <p><a href="https://www.clovekvtisni.cz" target="_blank">https://www.clovekvtisni.cz</a></p> <h4>Czech PR</h4> <p>Společnost poskytuje poradenské služby v oblasti vztahů s veřejností v České republice, provádí analýzy mediálního trhu a poskytuje komplexní služby v oblasti public relations.</p> <p>V roce 2016 nám agentura pomohla s analýzou našich vlastních strategických cílů a rozvojem CooLAND.</p> <p><a href="http://www.czechpr.cz/" target="_blank">http://www.czechpr.cz/</a></p> <h4>Kavárna Havran Café</h4> <p>Havran Café je malá a útulná kavárna v pražském Karlíně.</p> <p>CooLAND má v Havran Café svojí základnu, kde se scházíme a plánujeme. Od roku 2015 zde také každé úterý máme místo pro výdej zeleniny v rámci <a href="https://plus.google.com/u/0/communities/101783831094360976826" target="_blank">KPZ CooLAND</a>.</p> <p><a href="https://www.facebook.com/havrancafe/" target="_blank">https://www.facebook.com/havrancafe/</a></p> <h4>Nadace Via</h4> <p>Posláním nadace je otevírání cest k umění žít spolu a umění darovat. Nadace podporuje, vzdělává a propojuje lidi, kteří společně pečují o své okolí a kteří darují druhým. </p> <p>CooLAND byl v roce 2015-16 zařazen do projektu <a href="http://www.nadacevia.cz/viadukt/" target="_blank">VIADUKT</a>, který se zaměřuje na vzdělávání lidí z neziskovek.</p> <p><a href="http://www.nadacevia.cz/" target="_blank">http://www.nadacevia.cz/</a></p> </div> </body> <div id="footer"></div> </html>
tjelen/page-cooland
partaci.html
HTML
mit
15,062
#contact-info { font-size: .8em; } .job { background-color: #e9e5dc ; border-radius: 10px; margin-top: 5px; padding: .5px; } .ul { font-size: .8em; } li:last-child { color: blue; } #hula { color: red; }
LucasEWright/phase-0-tracks
css/css-demo/practice.css
CSS
mit
216
<div class="modal-header"> <h3 class="modal-title">Ohje</h3> </div> <div class="modal-body"> <div ng-show="createOwnNetwork"> <div class="help-element"> <img class="help-image" src="public/system/assets/img/infoimages/create.png"> <p> Voit perustaa oman verkostosi painamalla Luo oma Verkosto -painiketta. Luotuasi verkoston ilmestyt kartalle antamaasi sijaintiin.</p> </div> <div class="help-element"> <img class="help-image" src="public/system/assets/img/infoimages/gather.png"> <p> Luodessasi verkostosi saat samalla uniikin linkin, jota voit jakaa ystävillesi sosiaalisessa mediassa ja kutsua heidät liittymään osaksi sinun verkostoasi.</p> </div> </div> <div ng-hide="createOwnNetwork"> <div class="help-element"> <img class="help-image" src="public/system/assets/img/infoimages/Join.png"> <p> Tulit sivustolle käyttäjän {{founderName}} linkin kautta</p> <p>Lähde mukaan!-painikkeella pääset mukaan hänen verkostoon.</p> </div> <div class="help-element"> <img class="help-image" src="public/system/assets/img/infoimages/gather.png"> <p> Liittymällä {{founderName}} verkostoon luot oman verkoston, johon voit kutsua ystäviäsi mukaan toimimaan SOS hyväntekijöinä.</p> </div> </div> </div> <div class="modal-footer"> <b style="color:#00adef;"><i> Vikatilanteissa ota yhteyttä Tarmoon </i></b> <button class="btn btn-custom btn-lg" ng-click="ok()">Sulje</button> </div>
cybercom-finland/sos-app
public/system/views/helpWindow.html
HTML
mit
1,659
import Vue from 'vue'; import merge from 'element-ui/src/utils/merge'; import PopupManager from 'element-ui/src/utils/popup/popup-manager'; import getScrollBarWidth from '../scrollbar-width'; let idSeed = 1; const transitions = []; const hookTransition = (transition) => { if (transitions.indexOf(transition) !== -1) return; const getVueInstance = (element) => { let instance = element.__vue__; if (!instance) { const textNode = element.previousSibling; if (textNode.__vue__) { instance = textNode.__vue__; } } return instance; }; Vue.transition(transition, { afterEnter(el) { const instance = getVueInstance(el); if (instance) { instance.doAfterOpen && instance.doAfterOpen(); } }, afterLeave(el) { const instance = getVueInstance(el); if (instance) { instance.doAfterClose && instance.doAfterClose(); } } }); }; let scrollBarWidth; const getDOM = function(dom) { if (dom.nodeType === 3) { dom = dom.nextElementSibling || dom.nextSibling; getDOM(dom); } return dom; }; export default { model: { prop: 'visible', event: 'visible-change' }, props: { visible: { type: Boolean, default: false }, transition: { type: String, default: '' }, openDelay: {}, closeDelay: {}, zIndex: {}, modal: { type: Boolean, default: false }, modalFade: { type: Boolean, default: true }, modalClass: {}, modalAppendToBody: { type: Boolean, default: false }, lockScroll: { type: Boolean, default: true }, closeOnPressEscape: { type: Boolean, default: false }, closeOnClickModal: { type: Boolean, default: false } }, created() { if (this.transition) { hookTransition(this.transition); } }, beforeMount() { this._popupId = 'popup-' + idSeed++; PopupManager.register(this._popupId, this); }, beforeDestroy() { PopupManager.deregister(this._popupId); PopupManager.closeModal(this._popupId); if (this.modal && this.bodyOverflow !== null && this.bodyOverflow !== 'hidden') { document.body.style.overflow = this.bodyOverflow; document.body.style.paddingRight = this.bodyPaddingRight; } this.bodyOverflow = null; this.bodyPaddingRight = null; }, data() { return { opened: false, bodyOverflow: null, bodyPaddingRight: null, rendered: false }; }, watch: { visible(val) { if (val) { if (this._opening) return; if (!this.rendered) { this.rendered = true; Vue.nextTick(() => { this.open(); }); } else { this.open(); } } else { this.close(); } } }, methods: { open(options) { if (!this.rendered) { this.rendered = true; this.$emit('visible-change', true); } const props = merge({}, this.$props || this, options); if (this._closeTimer) { clearTimeout(this._closeTimer); this._closeTimer = null; } clearTimeout(this._openTimer); const openDelay = Number(props.openDelay); if (openDelay > 0) { this._openTimer = setTimeout(() => { this._openTimer = null; this.doOpen(props); }, openDelay); } else { this.doOpen(props); } }, doOpen(props) { if (this.$isServer) return; if (this.willOpen && !this.willOpen()) return; if (this.opened) return; this._opening = true; this.$emit('visible-change', true); const dom = getDOM(this.$el); const modal = props.modal; const zIndex = props.zIndex; if (zIndex) { PopupManager.zIndex = zIndex; } if (modal) { if (this._closing) { PopupManager.closeModal(this._popupId); this._closing = false; } PopupManager.openModal(this._popupId, PopupManager.nextZIndex(), this.modalAppendToBody ? undefined : dom, props.modalClass, props.modalFade); if (props.lockScroll) { if (!this.bodyOverflow) { this.bodyPaddingRight = document.body.style.paddingRight; this.bodyOverflow = document.body.style.overflow; } scrollBarWidth = getScrollBarWidth(); let bodyHasOverflow = document.documentElement.clientHeight < document.body.scrollHeight; if (scrollBarWidth > 0 && bodyHasOverflow) { document.body.style.paddingRight = scrollBarWidth + 'px'; } document.body.style.overflow = 'hidden'; } } if (getComputedStyle(dom).position === 'static') { dom.style.position = 'absolute'; } dom.style.zIndex = PopupManager.nextZIndex(); this.opened = true; this.onOpen && this.onOpen(); if (!this.transition) { this.doAfterOpen(); } }, doAfterOpen() { this._opening = false; }, close() { if (this.willClose && !this.willClose()) return; if (this._openTimer !== null) { clearTimeout(this._openTimer); this._openTimer = null; } clearTimeout(this._closeTimer); const closeDelay = Number(this.closeDelay); if (closeDelay > 0) { this._closeTimer = setTimeout(() => { this._closeTimer = null; this.doClose(); }, closeDelay); } else { this.doClose(); } }, doClose() { this.$emit('visible-change', false); this._closing = true; this.onClose && this.onClose(); if (this.lockScroll) { setTimeout(() => { if (this.modal && this.bodyOverflow !== 'hidden') { document.body.style.overflow = this.bodyOverflow; document.body.style.paddingRight = this.bodyPaddingRight; } this.bodyOverflow = null; this.bodyPaddingRight = null; }, 200); } this.opened = false; if (!this.transition) { this.doAfterClose(); } }, doAfterClose() { PopupManager.closeModal(this._popupId); this._closing = false; } } }; export { PopupManager };
JavascriptTips/element
src/utils/popup/index.js
JavaScript
mit
6,321
PowerShell ========== My PowerShell modules
nicholasdille/PowerShell
README.md
Markdown
mit
46
package edu.gatech.oad.antlab.pkg1; import edu.cs2335.antlab.pkg3.*; import edu.gatech.oad.antlab.person.*; import edu.gatech.oad.antlab.pkg2.*; /** * CS2335 Ant Lab * * Prints out a simple message gathered from all of the other classes * in the package structure */ public class AntLabMain { /**antlab11.java message class*/ private AntLab11 ant11; /**antlab12.java message class*/ private AntLab12 ant12; /**antlab21.java message class*/ private AntLab21 ant21; /**antlab22.java message class*/ private AntLab22 ant22; /**antlab31 java message class which is contained in a jar resource file*/ private AntLab31 ant31; /** * the constructor that intializes all the helper classes */ public AntLabMain () { ant11 = new AntLab11(); ant12 = new AntLab12(); ant21 = new AntLab21(); ant22 = new AntLab22(); ant31 = new AntLab31(); } /** * gathers a string from all the other classes and prints the message * out to the console * */ public void printOutMessage() { String toPrint = ant11.getMessage() + ant12.getMessage() + ant21.getMessage() + ant22.getMessage() + ant31.getMessage(); //Person1 replace P1 with your name //and gburdell1 with your gt id Person1 p1 = new Person1("Pranov"); toPrint += p1.toString("pduggasani3"); //Person2 replace P2 with your name //and gburdell with your gt id Person2 p2 = new Person2("Austin Dang"); toPrint += p2.toString("adang31"); //Person3 replace P3 with your name //and gburdell3 with your gt id Person3 p3 = new Person3("Jay Patel"); toPrint += p3.toString("jpatel345"); //Person4 replace P4 with your name //and gburdell4 with your gt id Person4 p4 = new Person4("Jin Chung"); toPrint += p4.toString("jchung89"); //Person5 replace P4 with your name //and gburdell5 with your gt id Person5 p5 = new Person5("Zachary Hussin"); toPrint += p5.toString("zhussin3"); System.out.println(toPrint); } /** * entry point for the program */ public static void main(String[] args) { new AntLabMain().printOutMessage(); } }
PranovD/CS2340
M2/src/main/java/edu/gatech/oad/antlab/pkg1/AntLabMain.java
Java
mit
2,551
package net.alloyggp.tournament.internal.admin; import net.alloyggp.escaperope.Delimiters; import net.alloyggp.escaperope.RopeDelimiter; import net.alloyggp.escaperope.rope.Rope; import net.alloyggp.escaperope.rope.ropify.SubclassWeaver; import net.alloyggp.escaperope.rope.ropify.Weaver; import net.alloyggp.tournament.api.TAdminAction; public class InternalAdminActions { private InternalAdminActions() { //Not instantiable } @SuppressWarnings("deprecation") public static final Weaver<TAdminAction> WEAVER = SubclassWeaver.builder(TAdminAction.class) .add(ReplaceGameAction.class, "ReplaceGame", ReplaceGameAction.WEAVER) .build(); public static RopeDelimiter getStandardDelimiter() { return Delimiters.getJsonArrayRopeDelimiter(); } public static TAdminAction fromPersistedString(String persistedString) { Rope rope = getStandardDelimiter().undelimit(persistedString); return WEAVER.fromRope(rope); } public static String toPersistedString(TAdminAction adminAction) { Rope rope = WEAVER.toRope(adminAction); return getStandardDelimiter().delimit(rope); } }
AlexLandau/ggp-tournament
src/main/java/net/alloyggp/tournament/internal/admin/InternalAdminActions.java
Java
mit
1,179
<div id="content-alerts"> <table id="conten-2" border="1px"> <tbody> <?php echo $sidemenu ?> <tr> <td style="vertical-align: top;"> <div style="padding: 5px 5px 5px 5px"> <table border="1" cellspacing="1px"> <tr style="background-color: #DBDBDB"> <th>ATM ID</th> <th>ĐẦU ĐỌC THẺ</th> <th>BỘ PHẬN TRẢ TIỀN</th> <th>BÀN PHÍM</th> <th>MÁY IN HÓA ĐƠN</th> <th>MẠNG</th> <th>SẴN SÀNG</th> </tr> <?php foreach ($result as $item) { echo "<tr>"; echo "<td>$item->AtmId</td>"; echo "<td>".(empty($item->CardReader) ? "OK" : "Lỗi")."</td>"; echo "<td>".(empty($item->CashDispenser) ? "OK" : "Lỗi")."</td>"; echo "<td>".(empty($item->PinPad) ? "OK" : "Lỗi")."</td>"; echo "<td>".(empty($item->ReceiptPrinter) ? "OK" : "Lỗi")."</td>"; echo "<td>".(empty($item->NetDown) ? "OK" : "Lỗi")."</td>"; echo "<td>".(empty($item->Service) ? "OK" : "Không")."</td>"; echo "</tr>"; } ?> </table> </div> </td> </tr> </tbody> </table> </div>
thaingochieu/atmphp
fuel/app/views/hoatdong/summary/atmerror.php
PHP
mit
1,690
<?xml version="1.0" ?><!DOCTYPE TS><TS language="hr" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About TelcoCoin</source> <translation>O TelcoCoin-u</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;TelcoCoin&lt;/b&gt; version</source> <translation>&lt;b&gt;TelcoCoin&lt;/b&gt; verzija</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation type="unfinished"/> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The TelcoCoin developers</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Adresar</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>Dvostruki klik za uređivanje adrese ili oznake</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Dodajte novu adresu</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Kopiraj trenutno odabranu adresu u međuspremnik</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>&amp;Nova adresa</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your TelcoCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation>Ovo su vaše TelcoCoin adrese za primanje isplate. Možda želite dati drukčiju adresu svakom primatelju tako da možete pratiti tko je platio.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation>&amp;Kopirati adresu</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>Prikaži &amp;QR Kôd</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a TelcoCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation>Izvoz podataka iz trenutnog taba u datoteku</translation> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified TelcoCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Brisanje</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your TelcoCoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation>Kopirati &amp;oznaku</translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>&amp;Izmjeniti</translation> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation type="unfinished"/> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>Izvoz podataka adresara</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Datoteka vrijednosti odvojenih zarezom (*. csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Pogreška kod izvoza</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Ne mogu pisati u datoteku %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Oznaka</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adresa</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(bez oznake)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Unesite lozinku</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Nova lozinka</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Ponovite novu lozinku</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Unesite novi lozinku za novčanik. &lt;br/&gt; Molimo Vas da koristite zaporku od &lt;b&gt;10 ili više slučajnih znakova,&lt;/b&gt; ili &lt;b&gt;osam ili više riječi.&lt;/b&gt;</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Šifriranje novčanika</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Ova operacija treba lozinku vašeg novčanika kako bi se novčanik otključao.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Otključaj novčanik</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Ova operacija treba lozinku vašeg novčanika kako bi se novčanik dešifrirao.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Dešifriranje novčanika.</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Promjena lozinke</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Unesite staru i novu lozinku za novčanik.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Potvrdi šifriranje novčanika</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR TelcoCoinS&lt;/b&gt;!</source> <translation>Upozorenje: Ako šifrirate vaš novčanik i izgubite lozinku, &lt;b&gt;IZGUBIT ĆETE SVE SVOJE TelcoCoinSE!&lt;/b&gt;</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Jeste li sigurni da želite šifrirati svoj novčanik?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation type="unfinished"/> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>Novčanik šifriran</translation> </message> <message> <location line="-56"/> <source>TelcoCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your TelcoCoins from being stolen by malware infecting your computer.</source> <translation>TelcoCoin će se sada zatvoriti kako bi dovršio postupak šifriranja. Zapamtite da šifriranje vašeg novčanika ne može u potpunosti zaštititi vaše TelcoCoine od krađe preko zloćudnog softvera koji bi bio na vašem računalu.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Šifriranje novčanika nije uspjelo</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Šifriranje novčanika nije uspjelo zbog interne pogreške. Vaš novčanik nije šifriran.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>Priložene lozinke se ne podudaraju.</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>Otključavanje novčanika nije uspjelo</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Lozinka za dešifriranje novčanika nije točna.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Dešifriranje novčanika nije uspjelo</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Lozinka novčanika je uspješno promijenjena.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation>&amp;Potpišite poruku...</translation> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation>Usklađivanje s mrežom ...</translation> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation>&amp;Pregled</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Prikaži opći pregled novčanika</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>&amp;Transakcije</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Pretraži povijest transakcija</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels for sending</source> <translation>Uređivanje popisa pohranjenih adresa i oznaka</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>Prikaži popis adresa za primanje isplate</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>&amp;Izlaz</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Izlazak iz programa</translation> </message> <message> <location line="+4"/> <source>Show information about TelcoCoin</source> <translation>Prikaži informacije o TelcoCoinu</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>Više o &amp;Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Prikaži informacije o Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Postavke</translation> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Šifriraj novčanik...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Backup novčanika...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>&amp;Promijena lozinke...</translation> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation>Importiranje blokova sa diska...</translation> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation>Re-indeksiranje blokova na disku...</translation> </message> <message> <location line="-347"/> <source>Send coins to a TelcoCoin address</source> <translation>Slanje novca na TelcoCoin adresu</translation> </message> <message> <location line="+49"/> <source>Modify configuration options for TelcoCoin</source> <translation>Promijeni postavke konfiguracije za TelcoCoin</translation> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation>Napravite sigurnosnu kopiju novčanika na drugoj lokaciji</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Promijenite lozinku za šifriranje novčanika</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation type="unfinished"/> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation type="unfinished"/> </message> <message> <location line="-165"/> <location line="+530"/> <source>TelcoCoin</source> <translation>TelcoCoin</translation> </message> <message> <location line="-530"/> <source>Wallet</source> <translation>Novčanik</translation> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>&amp;About TelcoCoin</source> <translation>&amp;O TelcoCoinu</translation> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Sign messages with your TelcoCoin addresses to prove you own them</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified TelcoCoin addresses</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;Datoteka</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>&amp;Konfiguracija</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>&amp;Pomoć</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>Traka kartica</translation> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location line="+47"/> <source>TelcoCoin client</source> <translation>TelcoCoin klijent</translation> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to TelcoCoin network</source> <translation><numerusform>%n aktivna veza na TelcoCoin mrežu</numerusform><numerusform>%n aktivne veze na TelcoCoin mrežu</numerusform><numerusform>%n aktivnih veza na TelcoCoin mrežu</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation>Obrađeno %1 blokova povijesti transakcije.</translation> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Error</source> <translation>Greška</translation> </message> <message> <location line="+3"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>Ažurno</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>Ažuriranje...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>Poslana transakcija</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>Dolazna transakcija</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Datum:%1 Iznos:%2 Tip:%3 Adresa:%4 </translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid TelcoCoin address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Novčanik je &lt;b&gt;šifriran&lt;/b&gt; i trenutno &lt;b&gt;otključan&lt;/b&gt;</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Novčanik je &lt;b&gt;šifriran&lt;/b&gt; i trenutno &lt;b&gt;zaključan&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. TelcoCoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Izmjeni adresu</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Oznaka</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>Oznaka ovog upisa u adresar</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Adresa</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>Adresa ovog upisa u adresar. Može se mjenjati samo kod adresa za slanje.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>Nova adresa za primanje</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Nova adresa za slanje</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Uredi adresu za primanje</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Uredi adresu za slanje</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>Upisana adresa &quot;%1&quot; je već u adresaru.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid TelcoCoin address.</source> <translation>Upisana adresa &quot;%1&quot; nije valjana TelcoCoin adresa.</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Ne mogu otključati novčanik.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Stvaranje novog ključa nije uspjelo.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>TelcoCoin-Qt</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>version</source> <translation>verzija</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Upotreba:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>UI options</source> <translation>UI postavke</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation>Pokreni minimiziran</translation> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Postavke</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>&amp;Glavno</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Plati &amp;naknadu za transakciju</translation> </message> <message> <location line="+31"/> <source>Automatically start TelcoCoin after logging in to the system.</source> <translation>Automatski pokreni TelcoCoin kad se uključi računalo</translation> </message> <message> <location line="+3"/> <source>&amp;Start TelcoCoin on system login</source> <translation>&amp;Pokreni TelcoCoin kod pokretanja sustava</translation> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Automatically open the TelcoCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Automatski otvori port TelcoCoin klijenta na ruteru. To radi samo ako ruter podržava UPnP i ako je omogućen.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Mapiraj port koristeći &amp;UPnP</translation> </message> <message> <location line="+7"/> <source>Connect to the TelcoCoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation>Spojite se na Bitcon mrežu putem SOCKS proxy-a (npr. kod povezivanja kroz Tor)</translation> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation>&amp;Povezivanje putem SOCKS proxy-a:</translation> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>IP adresa proxy-a (npr. 127.0.0.1)</translation> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Port od proxy-a (npr. 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Prikaži samo ikonu u sistemskoj traci nakon minimiziranja prozora</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Minimiziraj u sistemsku traku umjesto u traku programa</translation> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>Minimizirati umjesto izaći iz aplikacije kada je prozor zatvoren. Kada je ova opcija omogućena, aplikacija će biti zatvorena tek nakon odabira Izlaz u izborniku.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>M&amp;inimiziraj kod zatvaranja</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>&amp;Prikaz</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting TelcoCoin.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Jedinica za prikazivanje iznosa:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Izaberite željeni najmanji dio TelcoCoina koji će biti prikazan u sučelju i koji će se koristiti za plaćanje.</translation> </message> <message> <location line="+9"/> <source>Whether to show TelcoCoin addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>&amp;Prikaži adrese u popisu transakcija</translation> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation type="unfinished"/> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation>Upozorenje</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting TelcoCoin.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation type="unfinished"/> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Oblik</translation> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the TelcoCoin network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-124"/> <source>Balance:</source> <translation>Stanje:</translation> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>Nepotvrđene:</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>Novčanik</translation> </message> <message> <location line="+107"/> <source>Immature:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Nedavne transakcije&lt;/b&gt;</translation> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation>Vaše trenutno stanje računa</translation> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>Ukupni iznos transakcija koje tek trebaju biti potvrđene, i još uvijek nisu uračunate u trenutni saldo</translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation type="unfinished"/> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start TelcoCoin: click-to-pay handler</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation>QR Code Dijalog</translation> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>Zatraži plaćanje</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>Iznos:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>Oznaka</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>Poruka:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>&amp;Spremi kao...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>Rezultirajući URI je predug, probajte umanjiti tekst za naslov / poruku.</translation> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation>PNG slike (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+339"/> <source>N/A</source> <translation type="unfinished"/> </message> <message> <location line="-217"/> <source>Client version</source> <translation type="unfinished"/> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation type="unfinished"/> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Network</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>Lanac blokova</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Trenutni broj blokova</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation>Procjenjeni ukupni broj blokova</translation> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>Posljednje vrijeme bloka</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show the TelcoCoin-Qt help message to get a list with possible TelcoCoin command-line options.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation type="unfinished"/> </message> <message> <location line="-260"/> <source>Build date</source> <translation type="unfinished"/> </message> <message> <location line="-104"/> <source>TelcoCoin - Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>TelcoCoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Open the TelcoCoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation type="unfinished"/> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the TelcoCoin RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+124"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Slanje novca</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>Pošalji k nekoliko primatelja odjednom</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>&amp;Dodaj primatelja</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>Obriši sva polja transakcija</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>Obriši &amp;sve</translation> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>Stanje:</translation> </message> <message> <location line="+10"/> <source>123.456 BTC</source> <translation>123,456 BTC</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Potvrdi akciju slanja</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>&amp;Pošalji</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; do %2 (%3)</translation> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Potvrdi slanje novca</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>Jeste li sigurni da želite poslati %1?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation>i</translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation>Adresa primatelja je nevaljala, molimo provjerite je ponovo.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>Iznos mora biti veći od 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>Iznos je veći od stanja računa.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>Iznos je veći od stanja računa kad se doda naknada za transakcije od %1.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Pronašli smo adresu koja se ponavlja. U svakom plaćanju program može svaku adresu koristiti samo jedanput.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Generirani novčići moraju pričekati nastanak 120 blokova prije nego što ih je moguće potrošiti. Kad ste generirali taj blok, on je bio emitiran u mrežu kako bi bio dodan postojećim lancima blokova. Ako ne uspije biti dodan, njegov status bit će promijenjen u &quot;nije prihvatljiv&quot; i on neće biti potrošiv. S vremena na vrijeme tako nešto se može desiti ako neki drugi nod približno istovremeno generira blok.</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>Oblik</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>&amp;Iznos:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>&amp;Primatelj plaćanja:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation>Unesite oznaku za ovu adresu kako bi ju dodali u vaš adresar</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>&amp;Oznaka:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation>Odaberite adresu iz adresara</translation> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Zalijepi adresu iz međuspremnika</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation>Ukloni ovog primatelja</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a TelcoCoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Unesite TelcoCoin adresu (npr. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation>&amp;Potpišite poruku</translation> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation>Možete potpisati poruke sa svojom adresom kako bi dokazali da ih posjedujete. Budite oprezni da ne potpisujete ništa mutno, jer bi vas phishing napadi mogli na prevaru natjerati da prepišete svoj identitet njima. Potpisujte samo detaljno objašnjene izjave sa kojima se slažete.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Unesite TelcoCoin adresu (npr. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation>Odaberite adresu iz adresara</translation> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation>Zalijepi adresu iz međuspremnika</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>Upišite poruku koju želite potpisati ovdje</translation> </message> <message> <location line="+7"/> <source>Signature</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this TelcoCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Obriši &amp;sve</translation> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Unesite TelcoCoin adresu (npr. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified TelcoCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a TelcoCoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Unesite TelcoCoin adresu (npr. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Enter TelcoCoin signature</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation type="unfinished"/> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The TelcoCoin developers</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>Otvoren do %1</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation>%1 nije dostupan</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/nepotvrđeno</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 potvrda</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>Status</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Datum</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Generiran</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>Od</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>Za</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>label</source> <translation>oznaka</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Uplaćeno</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>Nije prihvaćeno</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Zaduženje</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Naknada za transakciju</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Neto iznos</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Poruka</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Komentar</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation>Generirani novčići moraju pričekati nastanak 120 blokova prije nego što ih je moguće potrošiti. Kad ste generirali taj blok, on je bio emitiran u mrežu kako bi bio dodan postojećim lancima blokova. Ako ne uspije biti dodan, njegov status bit će promijenjen u &quot;nije prihvaćen&quot; i on neće biti potrošiv. S vremena na vrijeme tako nešto se može desiti ako neki drugi nod generira blok u približno isto vrijeme.</translation> </message> <message> <location line="+7"/> <source>Debug information</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Transaction</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Iznos</translation> </message> <message> <location line="+1"/> <source>true</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>false</source> <translation type="unfinished"/> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, još nije bio uspješno emitiran</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>nepoznato</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Detalji transakcije</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Ova panela prikazuje detaljni opis transakcije</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>Datum</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Tip</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adresa</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Iznos</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>Otvoren do %1</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>Nije na mreži (%1 potvrda)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>Nepotvrđen (%1 od %2 potvrda)</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>Potvrđen (%1 potvrda)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Generirano - Upozorenje: ovaj blok nije bio primljen od strane bilo kojeg drugog noda i vjerojatno neće biti prihvaćen!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Generirano, ali nije prihvaćeno</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>Primljeno s</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Primljeno od</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Poslano za</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Plaćanje samom sebi</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Rudareno</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(n/d)</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Status transakcije</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Datum i vrijeme kad je transakcija primljena</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Vrsta transakcije.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Odredište transakcije</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Iznos odbijen od ili dodan k saldu.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>Sve</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Danas</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Ovaj tjedan</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Ovaj mjesec</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Prošli mjesec</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Ove godine</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Raspon...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Primljeno s</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Poslano za</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Tebi</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Rudareno</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Ostalo</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Unesite adresu ili oznaku za pretraživanje</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Min iznos</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Kopirati adresu</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Kopirati oznaku</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Kopiraj iznos</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Izmjeniti oznaku</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation>Izvoz podataka transakcija</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Datoteka podataka odvojenih zarezima (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Potvrđeno</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Datum</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Tip</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Oznaka</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Adresa</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Iznos</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Izvoz pogreške</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Ne mogu pisati u datoteku %1.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Raspon:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>za</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation>Slanje novca</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation>Izvoz podataka iz trenutnog taba u datoteku</translation> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>TelcoCoin version</source> <translation>TelcoCoin verzija</translation> </message> <message> <location line="+102"/> <source>Usage:</source> <translation>Upotreba:</translation> </message> <message> <location line="-29"/> <source>Send command to -server or TelcoCoind</source> <translation>Pošalji komandu usluzi -server ili TelcoCoind</translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>Prikaži komande</translation> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation>Potraži pomoć za komandu</translation> </message> <message> <location line="+24"/> <source>Options:</source> <translation>Postavke:</translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: TelcoCoin.conf)</source> <translation>Odredi konfiguracijsku datoteku (ugrađeni izbor: TelcoCoin.conf)</translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: TelcoCoind.pid)</source> <translation>Odredi proces ID datoteku (ugrađeni izbor: TelcoCoin.pid)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Odredi direktorij za datoteke</translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Postavi cache za bazu podataka u MB (zadano:25)</translation> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 22556 or testnet: 44556)</source> <translation>Slušaj na &lt;port&gt;u (default: 22556 ili testnet: 44556)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Održavaj najviše &lt;n&gt; veza sa članovima (default: 125)</translation> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Prag za odspajanje članova koji se čudno ponašaju (default: 100)</translation> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Broj sekundi koliko se članovima koji se čudno ponašaju neće dopustiti da se opet spoje (default: 86400)</translation> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 22555 or testnet: 44555)</source> <translation>Prihvaćaj JSON-RPC povezivanje na portu broj &lt;port&gt; (ugrađeni izbor: 22555 or testnet: 44555)</translation> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation>Prihvati komande iz tekst moda i JSON-RPC</translation> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation>Izvršavaj u pozadini kao uslužnik i prihvaćaj komande</translation> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation>Koristi test mrežu</translation> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </message> <message> <location line="-80"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=TelcoCoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;TelcoCoin Alert&quot; admin@foo.com </source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. TelcoCoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>Upozorenje: -paytxfee je podešen na preveliki iznos. To je iznos koji ćete platiti za obradu transakcije.</translation> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong TelcoCoin will not work properly.</source> <translation>Upozorenje: Molimo provjerite jesu li datum i vrijeme na vašem računalu točni. Ako vaš sat ide krivo, TelcoCoin neće raditi ispravno.</translation> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation>Opcije za kreiranje bloka:</translation> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation>Poveži se samo sa određenim nodom</translation> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation type="unfinished"/> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation>Importiraj blokove sa vanjskog blk000??.dat fajla</translation> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation>Nevaljala -tor adresa: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation>Prihvati samo lance blokova koji se podudaraju sa ugrađenim checkpoint-ovima (default: 1)</translation> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp (default: 1)</source> <translation>Dodaj izlaz debuga na početak sa vremenskom oznakom</translation> </message> <message> <location line="+5"/> <source>SSL options: (see the TelcoCoin Wiki for SSL setup instructions)</source> <translation>SSL postavke: (za detalje o podešavanju SSL opcija vidi TelcoCoin Wiki)</translation> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Šalji trace/debug informacije na konzolu umjesto u debug.log datoteku</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation>Pošalji trace/debug informacije u debugger</translation> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation>Podesite maksimalnu veličinu bloka u bajtovima (default: 250000)</translation> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>Podesite minimalnu veličinu bloka u bajtovima (default: 0)</translation> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Odredi vremenski prozor za spajanje na mrežu u milisekundama (ugrađeni izbor: 5000)</translation> </message> <message> <location line="+4"/> <source>System error: </source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>Pokušaj koristiti UPnP da otvoriš port za uslugu (default: 0)</translation> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Pokušaj koristiti UPnP da otvoriš port za uslugu (default: 1 when listening)</translation> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation>Korisničko ime za JSON-RPC veze</translation> </message> <message> <location line="+4"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation>Lozinka za JSON-RPC veze</translation> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Dozvoli JSON-RPC povezivanje s određene IP adrese</translation> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Pošalji komande nodu na adresi &lt;ip&gt; (ugrađeni izbor: 127.0.0.1)</translation> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Izvršite naredbu kada se najbolji blok promjeni (%s u cmd je zamjenjen sa block hash)</translation> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation>Nadogradite novčanik u posljednji format.</translation> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Podesi memorijski prostor za ključeve na &lt;n&gt; (ugrađeni izbor: 100)</translation> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Ponovno pretraži lanac blokova za transakcije koje nedostaju</translation> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Koristi OpenSSL (https) za JSON-RPC povezivanje</translation> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation>Uslužnikov SSL certifikat (ugrađeni izbor: server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Uslužnikov privatni ključ (ugrađeni izbor: server.pem)</translation> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Prihvaljivi načini šifriranja (ugrađeni izbor: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation> </message> <message> <location line="+165"/> <source>This help message</source> <translation>Ova poruka za pomoć</translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Program ne može koristiti %s na ovom računalu (bind returned error %d, %s)</translation> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation>Poveži se kroz socks proxy</translation> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Dozvoli DNS upite za dodavanje nodova i povezivanje</translation> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation>Učitavanje adresa...</translation> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Greška kod učitavanja wallet.dat: Novčanik pokvaren</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of TelcoCoin</source> <translation>Greška kod učitavanja wallet.dat: Novčanik zahtjeva noviju verziju TelcoCoina</translation> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart TelcoCoin to complete</source> <translation>Novčanik je trebao prepravak: ponovo pokrenite TelcoCoin</translation> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation>Greška kod učitavanja wallet.dat</translation> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Nevaljala -proxy adresa: &apos;%s&apos;</translation> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Nevaljali iznos za opciju -paytxfee=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>Nevaljali iznos za opciju</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation>Nedovoljna sredstva</translation> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>Učitavanje indeksa blokova...</translation> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Unesite nod s kojim se želite spojiti and attempt to keep the connection open</translation> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. TelcoCoin is probably already running.</source> <translation>Program ne može koristiti %s na ovom računalu. TelcoCoin program je vjerojatno već pokrenut.</translation> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation>Naknada posredniku po KB-u koja će biti dodana svakoj transakciji koju pošalješ</translation> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation>Učitavanje novčanika...</translation> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation>Nije moguće novčanik vratiti na prijašnju verziju.</translation> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation>Nije moguće upisati zadanu adresu.</translation> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation>Rescaniranje</translation> </message> <message> <location line="-57"/> <source>Done loading</source> <translation>Učitavanje gotovo</translation> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation type="unfinished"/> </message> <message> <location line="-74"/> <source>Error</source> <translation>Greška</translation> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation type="unfinished"/> </message> </context> </TS>
telcocoin-project/telcocoin
src/qt/locale/bitcoin_hr.ts
TypeScript
mit
107,245
{{< layout}} {{$pageTitle}}Upload your photo{{/pageTitle}} {{$header}} <h1>Upload your photo</h1> {{/header}} {{$content}} <p >Your photo must be taken in the last month and meet the <br><a href="/../change_of_name_180122/photoguide-static/photorules"> rules for passport photos</a>.</p> <a href="/change_of_name_180122/uploadphoto/" class="button">Upload your photo</a><br/><br/> <div class="grid-row photo-upload-eg"> <div class="column-half img"> <object type="image/jpg" data="/public/images/woman-with-reddish-hair_ex@2x.jpg" type="image/svg+xml" class="svg" tabindex="-1"> <img src="/public/images/woman-with-reddish-hair_ex@2x.jpg" width="206" height= alt=""> </object> </div> <div class="column-half"> <h2>Taking a good photo</h2> <ol class="list list-number"> <li>Get a friend to take your photo.</li> <li>Use a plain background.</li> <li>Don’t crop your photo, include your face, shoulders and upper body.</li> <li>Keep your hair away from your face and brushed down.</li> <li>Make sure there are no shadows on your face or behind you.</li> </ol> </div> </div> <br/> <p> We keep all photos for up to 30 days in line with our <a href="https://www.passport.service.gov.uk/help/privacy" rel="external">privacy policy</a>. </p> {{/content}} {{/ layout}}
UKHomeOffice/passports-prototype
views/change_of_name_180122/upload/index.html
HTML
mit
1,507
. ~/hulk-bash/scripts/web.sh . ~/hulk-bash/.aliases
BennyHallett/hulk-bash
hulk.bash
Shell
mit
52
<?php namespace BungieNetPlatform\Exceptions\Platform; use BungieNetPlatform\Exceptions\PlatformException; /** * DestinyStatsParameterMembershipIdParseError */ class DestinyStatsParameterMembershipIdParseErrorException extends PlatformException { public function __construct($message, $code = 1608, \Exception $previous = null) { parent::__construct($message, $code, $previous); } }
dazarobbo/BungieNetPlatform
src/Exceptions/Platform/DestinyStatsParameterMembershipIdParseErrorException.php
PHP
mit
410
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"> <head> <title>System Manager Dashboard</title> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" th:href="@{/webjars/bootstrap/3.3.6/css/bootstrap.min.css}" /> <script th:src="@{/webjars/jquery/2.1.4/jquery.min.js}"></script> <script th:src="@{/webjars/bootstrap/3.3.6/js/bootstrap.min.js}"></script> <script> $(document).ready(function () { (function ($) { $('#filter').keyup(function () { var rex = new RegExp($(this).val(), 'i'); $('.searchable tr').hide(); $('.searchable tr').filter(function () { return rex.test($(this).text()); }).show(); }) }(jQuery)); }); </script> </head> <body> <nav class="navbar navbar-default"> <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <p class="navbar-brand">Cardinals Banking</p> </div> <ul class="nav navbar-nav navbar-right"> <li><a th:href="@{/manager/details}">My Dashboard</a></li> <li><a th:href="@{/logout}">Logout</a></li> </ul> </div> </nav> <div class="container"> <h3>System Manager Dashboard</h3> <ul class="nav nav-tabs nav-justified"> <li><a th:href="@{/manager/user}">View External User Accounts</a></li> <li><a th:href="@{/manager/details}">My Profile</a></li> <li><a th:href="@{/manager/user/request}">New External User Requests</a></li> <li><a th:href="@{/manager/employee/authorize}">Authorize Access</a></li> <li><a th:href="@{/manager/employee/request}">View Access Requests</a></li> <li class="active"><a href="#">Pending Transfers</a></li> <li><a th:href="@{/manager/transactions}">Pending Transactions</a></li> </ul> </div> <div class="container"> <div class="input-group"> <span class="input-group-addon">Filter</span> <input id="filter" type="text" class="form-control" placeholder="Type here..." /> </div> <div class="container"> <table class="table table-striped"> <thead> <tr> <th>From</th> <th>Account Number</th> <th>To</th> <th>Account Number</th> <th>Amount</th> </tr> </thead> <tbody class="searchable"> <tr th:each="transfer : ${transfers}"> <td th:text="${transfer.fromAccount.user.username}"></td> <td th:text="${transfer.fromAccount.accountNumber}"></td> <td th:text="${transfer.toAccount.user.username}"></td> <td th:text="${transfer.toAccount.accountNumber}"></td> <td th:text="${transfer.amount}"></td> <td><a th:href="@{/manager/transfer/{id}(id=${transfer.transferId})}">View</a></td> </tr> --> </tbody> </table> </div> </div> </body> </html>
Nikh13/securbank
src/main/resources/templates/manager/pendingtransfers.html
HTML
mit
2,902
((n|=2<<1))
grncdr/js-shell-parse
tests/fixtures/shellcheck-tests/arithmetic3/source.sh
Shell
mit
11
$LOAD_PATH.unshift File.expand_path('../lib') require 'rspec' RSpec.configure do |conf| conf.color = true conf.formatter = 'documentation' conf.order = 'random' end
timuruski/press_any_key
spec/spec_helper.rb
Ruby
mit
173
var eejs = require('ep_etherpad-lite/node/eejs') /* * Handle incoming delete requests from clients */ exports.handleMessage = function(hook_name, context, callback){ var Pad = require('ep_etherpad-lite/node/db/Pad.js').Pad // Firstly ignore any request that aren't about chat var isDeleteRequest = false; if(context) { if(context.message && context.message){ if(context.message.type === 'COLLABROOM'){ if(context.message.data){ if(context.message.data.type){ if(context.message.data.type === 'ep_push2delete'){ isDeleteRequest = true; } } } } } } if(!isDeleteRequest){ callback(false); return false; } console.log('DELETION REQUEST!') var packet = context.message.data; /*** What's available in a packet? * action -- The action IE chatPosition * padId -- The padId of the pad both authors are on ***/ if(packet.action === 'deletePad'){ var pad = new Pad(packet.padId) pad.remove(function(er) { if(er) console.warn('ep_push2delete', er) callback([null]); }) } } exports.eejsBlock_editbarMenuRight = function(hook_name, args, cb) { if(!args.renderContext.req.url.match(/^\/(p\/r\..{16})/)) { args.content = eejs.require('ep_push2delete/templates/delete_button.ejs') + args.content; } cb(); };
marcelklehr/ep_push2delete
index.js
JavaScript
mit
1,374
using Microsoft.Xna.Framework; using System; namespace Gem.Gui.Animations { public static class Time { public static Animation<double> Elapsed { get { return Animation.Create(context => context.TotalMilliseconds); } } public static Animation<TTime> Constant<TTime>(TTime time) { return Animation.Create(context => time); } public static Animation<double> Wave { get { return Animation.Create(context => Math.Sin(context.TotalSeconds)); } } } }
gmich/Gem
Gem.Gui/Animations/Time.cs
C#
mit
610
version https://git-lfs.github.com/spec/v1 oid sha256:355954a2b585f8b34c53b8bea9346fabde06b161ec86b87e9b829bea4acb87e9 size 108190
yogeshsaroya/new-cdnjs
ajax/libs/materialize/0.95.0/js/materialize.min.js
JavaScript
mit
131
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Coq bench</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../../..">Unstable</a></li> <li><a href=".">8.4.dev / contrib:sudoku 8.4.dev</a></li> <li class="active"><a href="">2015-01-30 03:04:02</a></li> </ul> <ul class="nav navbar-nav navbar-right"> <li><a href="../../../../../about.html">About</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href=".">« Up</a> <h1> contrib:sudoku <small> 8.4.dev <span class="label label-success">41 s</span> </small> </h1> <p><em><script>document.write(moment("2015-01-30 03:04:02 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2015-01-30 03:04:02 UTC)</em><p> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>ruby lint.rb unstable ../unstable/packages/coq:contrib:sudoku/coq:contrib:sudoku.8.4.dev</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> <dt>Output</dt> <dd><pre>The package is valid. </pre></dd> </dl> <h2>Dry install</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --dry-run coq:contrib:sudoku.8.4.dev coq.8.4.dev</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>2 s</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.4.dev). The following actions will be performed: - install coq:contrib:sudoku.8.4.dev === 1 to install === =-=- Synchronizing package archives -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= =-=- Installing packages =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= Building coq:contrib:sudoku.8.4.dev: coq_makefile -f Make -o Makefile make -j4 make install Installing coq:contrib:sudoku.8.4.dev. </pre></dd> </dl> <p>Dry install without Coq, to test if the problem was incompatibility with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>ulimit -Sv 2000000; timeout 5m opam install -y --deps-only coq:contrib:sudoku.8.4.dev</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>2 s</dd> </dl> <h2>Install</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>ulimit -Sv 2000000; timeout 5m opam install -y --verbose coq:contrib:sudoku.8.4.dev</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>41 s</dd> <dt>Output</dt> <dd><pre>The following actions will be performed: - install coq:contrib:sudoku.8.4.dev === 1 to install === =-=- Synchronizing package archives -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= [coq:contrib:sudoku] Fetching https://gforge.inria.fr/git/coq-contribs/sudoku.git#v8.4 Initialized empty Git repository in /home/bench/.opam/packages.dev/coq:contrib:sudoku.8.4.dev/.git/ [master (root-commit) 479e1a9] opam-git-init From https://gforge.inria.fr/git/coq-contribs/sudoku * [new branch] v8.4 -&gt; opam-ref * [new branch] v8.4 -&gt; origin/v8.4 Div.v LICENSE ListAux.v ListOp.v Make Makefile Note.pdf OrderedList.v Permutation.v README Sudoku.v Tactic.v Test.v UList.v bench.log description HEAD is now at 71a653c Removing useless calls to injection. =-=- Installing packages =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= Building coq:contrib:sudoku.8.4.dev: coq_makefile -f Make -o Makefile make -j4 make install &quot;coqdep&quot; -c -slash -R . Sudoku &quot;Div.v&quot; &gt; &quot;Div.v.d&quot; || ( RV=$?; rm -f &quot;Div.v.d&quot;; exit ${RV} ) &quot;coqdep&quot; -c -slash -R . Sudoku &quot;ListAux.v&quot; &gt; &quot;ListAux.v.d&quot; || ( RV=$?; rm -f &quot;ListAux.v.d&quot;; exit ${RV} ) &quot;coqdep&quot; -c -slash -R . Sudoku &quot;ListOp.v&quot; &gt; &quot;ListOp.v.d&quot; || ( RV=$?; rm -f &quot;ListOp.v.d&quot;; exit ${RV} ) &quot;coqdep&quot; -c -slash -R . Sudoku &quot;OrderedList.v&quot; &gt; &quot;OrderedList.v.d&quot; || ( RV=$?; rm -f &quot;OrderedList.v.d&quot;; exit ${RV} ) &quot;coqdep&quot; -c -slash -R . Sudoku &quot;Permutation.v&quot; &gt; &quot;Permutation.v.d&quot; || ( RV=$?; rm -f &quot;Permutation.v.d&quot;; exit ${RV} ) &quot;coqdep&quot; -c -slash -R . Sudoku &quot;Sudoku.v&quot; &gt; &quot;Sudoku.v.d&quot; || ( RV=$?; rm -f &quot;Sudoku.v.d&quot;; exit ${RV} ) &quot;coqdep&quot; -c -slash -R . Sudoku &quot;Tactic.v&quot; &gt; &quot;Tactic.v.d&quot; || ( RV=$?; rm -f &quot;Tactic.v.d&quot;; exit ${RV} ) &quot;coqdep&quot; -c -slash -R . Sudoku &quot;Test.v&quot; &gt; &quot;Test.v.d&quot; || ( RV=$?; rm -f &quot;Test.v.d&quot;; exit ${RV} ) &quot;coqdep&quot; -c -slash -R . Sudoku &quot;UList.v&quot; &gt; &quot;UList.v.d&quot; || ( RV=$?; rm -f &quot;UList.v.d&quot;; exit ${RV} ) &quot;coqc&quot; -q -R . Sudoku Tactic &quot;coqc&quot; -q -R . Sudoku ListAux &quot;coqc&quot; -q -R . Sudoku Div &quot;coqc&quot; -q -R . Sudoku Permutation &quot;coqc&quot; -q -R . Sudoku UList &quot;coqc&quot; -q -R . Sudoku OrderedList &quot;coqc&quot; -q -R . Sudoku ListOp &quot;coqc&quot; -q -R . Sudoku Sudoku &quot;coqc&quot; -q -R . Sudoku Test = 288 : nat = 2 :: 5 :: 8 :: 1 :: 6 :: 4 :: 9 :: 7 :: 3 :: nil : list nat = 6 :: 3 :: 4 :: 9 :: 5 :: 7 :: 2 :: 1 :: 8 :: nil : list nat = 9 :: 7 :: 1 :: 2 :: 3 :: 8 :: 6 :: 4 :: 5 :: nil : list nat = 7 :: 4 :: 5 :: 3 :: 9 :: 1 :: 8 :: 2 :: 6 :: nil : list nat = 8 :: 9 :: 6 :: 4 :: 2 :: 5 :: 1 :: 3 :: 7 :: nil : list nat = 1 :: 2 :: 3 :: 7 :: 8 :: 6 :: 4 :: 5 :: 9 :: nil : list nat = 3 :: 6 :: 9 :: 5 :: 1 :: 2 :: 7 :: 8 :: 4 :: nil : list nat = 4 :: 8 :: 2 :: 6 :: 7 :: 3 :: 5 :: 9 :: 1 :: nil : list nat = 5 :: 1 :: 7 :: 8 :: 4 :: 9 :: 3 :: 6 :: 2 :: nil : list nat = 1 : nat = 4 :: 5 :: 6 :: 9 :: 8 :: 7 :: 2 :: 1 :: 3 :: nil : list nat = 8 :: 3 :: 9 :: 2 :: 1 :: 5 :: 7 :: 6 :: 4 :: nil : list nat = 1 :: 2 :: 7 :: 6 :: 4 :: 3 :: 8 :: 5 :: 9 :: nil : list nat = 7 :: 4 :: 2 :: 3 :: 6 :: 9 :: 5 :: 8 :: 1 :: nil : list nat = 5 :: 6 :: 3 :: 8 :: 2 :: 1 :: 4 :: 9 :: 7 :: nil : list nat = 9 :: 8 :: 1 :: 7 :: 5 :: 4 :: 6 :: 3 :: 2 :: nil : list nat = 2 :: 7 :: 8 :: 1 :: 3 :: 6 :: 9 :: 4 :: 5 :: nil : list nat = 6 :: 1 :: 5 :: 4 :: 9 :: 2 :: 3 :: 7 :: 8 :: nil : list nat = 3 :: 9 :: 4 :: 5 :: 7 :: 8 :: 1 :: 2 :: 6 :: nil : list nat = 1 :: 2 :: 3 :: 4 :: 5 :: 6 :: 7 :: 8 :: 9 :: nil : list nat = 7 :: 8 :: 9 :: 1 :: 2 :: 3 :: 4 :: 5 :: 6 :: nil : list nat = 4 :: 5 :: 6 :: 9 :: 7 :: 8 :: 1 :: 2 :: 3 :: nil : list nat = 9 :: 1 :: 2 :: 8 :: 6 :: 5 :: 3 :: 4 :: 7 :: nil : list nat = 8 :: 3 :: 4 :: 7 :: 1 :: 2 :: 9 :: 6 :: 5 :: nil : list nat = 5 :: 6 :: 7 :: 3 :: 4 :: 9 :: 8 :: 1 :: 2 :: nil : list nat = 2 :: 9 :: 1 :: 5 :: 3 :: 4 :: 6 :: 7 :: 8 :: nil : list nat = 3 :: 7 :: 5 :: 6 :: 8 :: 1 :: 2 :: 9 :: 4 :: nil : list nat = 6 :: 4 :: 8 :: 2 :: 9 :: 7 :: 5 :: 3 :: 1 :: nil : list nat = Some (1 :: nil) : option (list nat) = Some (1 :: 2 :: 2 :: 1 :: nil) : option (list nat) = Some (1 :: 2 :: 3 :: 4 :: 3 :: 4 :: 1 :: 2 :: 2 :: 1 :: 4 :: 3 :: 4 :: 3 :: 2 :: 1 :: nil) : option (list nat) = Some (1 :: 2 :: 3 :: 4 :: 5 :: 6 :: 5 :: 6 :: 1 :: 2 :: 3 :: 4 :: 3 :: 4 :: 5 :: 6 :: 1 :: 2 :: 2 :: 1 :: 4 :: 3 :: 6 :: 5 :: 6 :: 5 :: 2 :: 1 :: 4 :: 3 :: 4 :: 3 :: 6 :: 5 :: 2 :: 1 :: nil) : option (list nat) = Some (1 :: 2 :: 3 :: 4 :: 5 :: 6 :: 7 :: 8 :: 9 :: 7 :: 8 :: 9 :: 1 :: 2 :: 3 :: 4 :: 5 :: 6 :: 4 :: 5 :: 6 :: 9 :: 7 :: 8 :: 1 :: 2 :: 3 :: 9 :: 1 :: 2 :: 8 :: 6 :: 5 :: 3 :: 4 :: 7 :: 8 :: 3 :: 4 :: 7 :: 1 :: 2 :: 9 :: 6 :: 5 :: 5 :: ..) : option (list nat) Finished transaction in 1. secs (1.812374u,1.8e-05s) = 7 :: 2 :: 4 :: 9 :: 6 :: 5 :: 8 :: 3 :: 1 :: nil : list nat = 6 :: 3 :: 5 :: 1 :: 4 :: 8 :: 9 :: 2 :: 7 :: nil : list nat = 1 :: 8 :: 9 :: 2 :: 7 :: 3 :: 4 :: 5 :: 6 :: nil : list nat = 2 :: 6 :: 1 :: 4 :: 8 :: 9 :: 3 :: 7 :: 5 :: nil : list nat = 9 :: 5 :: 8 :: 6 :: 3 :: 7 :: 1 :: 4 :: 2 :: nil : list nat = 3 :: 4 :: 7 :: 5 :: 2 :: 1 :: 6 :: 9 :: 8 :: nil : list nat = 5 :: 7 :: 6 :: 3 :: 1 :: 4 :: 2 :: 8 :: 9 :: nil : list nat = 4 :: 9 :: 2 :: 8 :: 5 :: 6 :: 7 :: 1 :: 3 :: nil : list nat = 8 :: 1 :: 3 :: 7 :: 9 :: 2 :: 5 :: 6 :: 4 :: nil : list nat = 25 : nat Finished transaction in 6. secs (6.283789u,1.1e-05s) Finished transaction in 3. secs (3.29798u,8.00000000001e-06s) = 5 :: 8 :: 6 :: 2 :: 3 :: 7 :: 9 :: 1 :: 4 :: nil : list nat = 7 :: 4 :: 2 :: 8 :: 1 :: 9 :: 3 :: 5 :: 6 :: nil : list nat = 1 :: 9 :: 3 :: 4 :: 6 :: 5 :: 7 :: 8 :: 2 :: nil : list nat = 6 :: 5 :: 7 :: 9 :: 8 :: 1 :: 2 :: 4 :: 3 :: nil : list nat = 9 :: 1 :: 4 :: 7 :: 2 :: 3 :: 5 :: 6 :: 8 :: nil : list nat = 2 :: 3 :: 8 :: 5 :: 4 :: 6 :: 1 :: 7 :: 9 :: nil : list nat = 3 :: 6 :: 5 :: 1 :: 9 :: 8 :: 4 :: 2 :: 7 :: nil : list nat = 4 :: 7 :: 9 :: 6 :: 5 :: 2 :: 8 :: 3 :: 1 :: nil : list nat = 8 :: 2 :: 1 :: 3 :: 7 :: 4 :: 6 :: 9 :: 5 :: nil : list nat = 1 : nat Finished transaction in 3. secs (3.310704u,0.s) for i in UList.vo Test.vo Tactic.vo Sudoku.vo Permutation.vo OrderedList.vo ListOp.vo ListAux.vo Div.vo; do \ install -d `dirname &quot;/home/bench/.opam/system/lib/coq/user-contrib&quot;/Sudoku/$i`; \ install -m 0644 $i &quot;/home/bench/.opam/system/lib/coq/user-contrib&quot;/Sudoku/$i; \ done Installing coq:contrib:sudoku.8.4.dev. </pre></dd> </dl> <h2>Installation size</h2> <p>Total: 963 K</p> <ul> <li>413 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Sudoku/Sudoku.vo</code></li> <li>167 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Sudoku/Permutation.vo</code></li> <li>111 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Sudoku/OrderedList.vo</code></li> <li>87 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Sudoku/ListAux.vo</code></li> <li>69 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Sudoku/UList.vo</code></li> <li>42 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Sudoku/ListOp.vo</code></li> <li>32 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Sudoku/Test.vo</code></li> <li>31 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Sudoku/Div.vo</code></li> <li>7 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Sudoku/Tactic.vo</code></li> <li>1 K <code>/home/bench/.opam/system/lib/coq:contrib:sudoku/opam.config</code></li> <li>1 K <code>/home/bench/.opam/system/install/coq:contrib:sudoku.install</code></li> </ul> <h2>Uninstall</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq:contrib:sudoku.8.4.dev</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>2 s</dd> <dt>Output</dt> <dd><pre>The following actions will be performed: - remove coq:contrib:sudoku.8.4.dev === 1 to remove === =-=- Synchronizing package archives -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= [coq:contrib:sudoku] Fetching https://gforge.inria.fr/git/coq-contribs/sudoku.git#v8.4 =-=- Removing Packages =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= Removing coq:contrib:sudoku.8.4.dev. rm -R /home/bench/.opam/system/lib/coq/user-contrib/Sudoku </pre></dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> <small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small> </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
coq-bench/coq-bench.github.io-old
clean/Linux-x86_64-4.01.0-1.2.0/unstable/8.4.dev/contrib:sudoku/8.4.dev/2015-01-30_03-04-02.html
HTML
mit
20,619
using Robust.Shared.GameObjects; namespace Content.Server.MachineLinking.Components { [RegisterComponent] public sealed class TriggerOnSignalReceivedComponent : Component { } }
space-wizards/space-station-14
Content.Server/MachineLinking/Components/TriggerOnSignalReceivedComponent.cs
C#
mit
197
//#include <stdio.h> //#include <stdlib.h> //#include <stdint.h> //#include <stdbool.h> //#include <string.h> //#include <stddef.h> #include "esp_common.h" #include "coap.h" #include "shell.h" //#include <rtthread.h> //#define shell_printf rt_kshell_printf extern void endpoint_setup(void); extern const coap_endpoint_t endpoints[]; #ifdef MICROCOAP_DEBUG void ICACHE_FLASH_ATTR coap_dumpHeader(coap_header_t *hdr) { shell_printf("Header:\n"); shell_printf(" ver 0x%02X\n", hdr->ver); shell_printf(" t 0x%02X\n", hdr->t); shell_printf(" tkl 0x%02X\n", hdr->tkl); shell_printf(" code 0x%02X\n", hdr->code); shell_printf(" id 0x%02X%02X\n", hdr->id[0], hdr->id[1]); } #endif #ifdef MICROCOAP_DEBUG void ICACHE_FLASH_ATTR coap_dump(const uint8_t *buf, size_t buflen, bool bare) { if (bare) { while(buflen--) shell_printf("%02X%s", *buf++, (buflen > 0) ? " " : ""); } else { shell_printf("Dump: "); while(buflen--) shell_printf("%02X%s", *buf++, (buflen > 0) ? " " : ""); shell_printf("\n"); } } #endif int ICACHE_FLASH_ATTR coap_parseHeader(coap_header_t *hdr, const uint8_t *buf, size_t buflen) { if (buflen < 4) return COAP_ERR_HEADER_TOO_SHORT; hdr->ver = (buf[0] & 0xC0) >> 6; if (hdr->ver != 1) return COAP_ERR_VERSION_NOT_1; hdr->t = (buf[0] & 0x30) >> 4; hdr->tkl = buf[0] & 0x0F; hdr->code = buf[1]; hdr->id[0] = buf[2]; hdr->id[1] = buf[3]; return 0; } int ICACHE_FLASH_ATTR coap_parseToken(coap_buffer_t *tokbuf, const coap_header_t *hdr, const uint8_t *buf, size_t buflen) { if (hdr->tkl == 0) { tokbuf->p = NULL; tokbuf->len = 0; return 0; } else if (hdr->tkl <= 8) { if (4U + hdr->tkl > buflen) return COAP_ERR_TOKEN_TOO_SHORT; // tok bigger than packet tokbuf->p = buf+4; // past header tokbuf->len = hdr->tkl; return 0; } else { // invalid size return COAP_ERR_TOKEN_TOO_SHORT; } } // advances p int ICACHE_FLASH_ATTR coap_parseOption(coap_option_t *option, uint16_t *running_delta, const uint8_t **buf, size_t buflen) { const uint8_t *p = *buf; uint8_t headlen = 1; uint16_t len, delta; if (buflen < headlen) // too small return COAP_ERR_OPTION_TOO_SHORT_FOR_HEADER; delta = (p[0] & 0xF0) >> 4; len = p[0] & 0x0F; // These are untested and may be buggy if (delta == 13) { headlen++; if (buflen < headlen) return COAP_ERR_OPTION_TOO_SHORT_FOR_HEADER; delta = p[1] + 13; p++; } else if (delta == 14) { headlen += 2; if (buflen < headlen) return COAP_ERR_OPTION_TOO_SHORT_FOR_HEADER; delta = ((p[1] << 8) | p[2]) + 269; p+=2; } else if (delta == 15) return COAP_ERR_OPTION_DELTA_INVALID; if (len == 13) { headlen++; if (buflen < headlen) return COAP_ERR_OPTION_TOO_SHORT_FOR_HEADER; len = p[1] + 13; p++; } else if (len == 14) { headlen += 2; if (buflen < headlen) return COAP_ERR_OPTION_TOO_SHORT_FOR_HEADER; len = ((p[1] << 8) | p[2]) + 269; p+=2; } else if (len == 15) return COAP_ERR_OPTION_LEN_INVALID; if ((p + 1 + len) > (*buf + buflen)) return COAP_ERR_OPTION_TOO_BIG; //shell_printf("option num=%d\n", delta + *running_delta); option->num = delta + *running_delta; option->buf.p = p+1; option->buf.len = len; //coap_dump(p+1, len, false); // advance buf *buf = p + 1 + len; *running_delta += delta; return 0; } // http://tools.ietf.org/html/rfc7252#section-3.1 int ICACHE_FLASH_ATTR coap_parseOptionsAndPayload(coap_option_t *options, uint8_t *numOptions, coap_buffer_t *payload, const coap_header_t *hdr, const uint8_t *buf, size_t buflen) { size_t optionIndex = 0; uint16_t delta = 0; const uint8_t *p = buf + 4 + hdr->tkl; const uint8_t *end = buf + buflen; int rc; if (p > end) return COAP_ERR_OPTION_OVERRUNS_PACKET; // out of bounds //coap_dump(p, end - p); // 0xFF is payload marker while((optionIndex < *numOptions) && (p < end) && (*p != 0xFF)) { if (0 != (rc = coap_parseOption(&options[optionIndex], &delta, &p, end-p))) return rc; optionIndex++; } *numOptions = optionIndex; if (p+1 < end && *p == 0xFF) // payload marker { payload->p = p+1; payload->len = end-(p+1); } else { payload->p = NULL; payload->len = 0; } return 0; } #ifdef MICROCOAP_DEBUG void ICACHE_FLASH_ATTR coap_dumpOptions(coap_option_t *opts, size_t numopt) { size_t i; shell_printf("Options:\n"); for (i=0;i<numopt;i++) { shell_printf(" 0x%02X [ ", opts[i].num); coap_dump(opts[i].buf.p, opts[i].buf.len, true); shell_printf(" ]\n"); } } #endif #ifdef MICROCOAP_DEBUG void ICACHE_FLASH_ATTR coap_dumpPacket(coap_packet_t *pkt) { coap_dumpHeader(&pkt->hdr); coap_dumpOptions(pkt->opts, pkt->numopts); shell_printf("Payload: \n"); coap_dump(pkt->payload.p, pkt->payload.len, true); shell_printf("\n"); } #endif int ICACHE_FLASH_ATTR coap_parse(coap_packet_t *pkt, const uint8_t *buf, size_t buflen) { int rc; // coap_dump(buf, buflen, false); if (0 != (rc = coap_parseHeader(&pkt->hdr, buf, buflen))) return rc; // coap_dumpHeader(&hdr); if (0 != (rc = coap_parseToken(&pkt->tok, &pkt->hdr, buf, buflen))) return rc; pkt->numopts = MAXOPT; if (0 != (rc = coap_parseOptionsAndPayload(pkt->opts, &(pkt->numopts), &(pkt->payload), &pkt->hdr, buf, buflen))) return rc; // coap_dumpOptions(opts, numopt); return 0; } // options are always stored consecutively, so can return a block with same option num const coap_option_t * ICACHE_FLASH_ATTR coap_findOptions(const coap_packet_t *pkt, uint8_t num, uint8_t *count) { // FIXME, options is always sorted, can find faster than this size_t i; const coap_option_t *first = NULL; *count = 0; for (i=0;i<pkt->numopts;i++) { if (pkt->opts[i].num == num) { if (NULL == first) first = &pkt->opts[i]; (*count)++; } else { if (NULL != first) break; } } return first; } int ICACHE_FLASH_ATTR coap_buffer_to_string(char *strbuf, size_t strbuflen, const coap_buffer_t *buf) { if (buf->len+1 > strbuflen) return COAP_ERR_BUFFER_TOO_SMALL; memcpy(strbuf, buf->p, buf->len); strbuf[buf->len] = 0; return 0; } int ICACHE_FLASH_ATTR coap_build(uint8_t *buf, size_t *buflen, const coap_packet_t *pkt) { size_t opts_len = 0; size_t i; uint8_t *p; uint16_t running_delta = 0; // build header if (*buflen < (4U + pkt->hdr.tkl)) return COAP_ERR_BUFFER_TOO_SMALL; buf[0] = (pkt->hdr.ver & 0x03) << 6; buf[0] |= (pkt->hdr.t & 0x03) << 4; buf[0] |= (pkt->hdr.tkl & 0x0F); buf[1] = pkt->hdr.code; buf[2] = pkt->hdr.id[0]; buf[3] = pkt->hdr.id[1]; // inject token p = buf + 4; if ((pkt->hdr.tkl > 0) && (pkt->hdr.tkl != pkt->tok.len)) return COAP_ERR_UNSUPPORTED; if (pkt->hdr.tkl > 0) memcpy(p, pkt->tok.p, pkt->hdr.tkl); // // http://tools.ietf.org/html/rfc7252#section-3.1 // inject options p += pkt->hdr.tkl; for (i=0;i<pkt->numopts;i++) { uint32_t optDelta; uint8_t len, delta = 0; if (((size_t)(p-buf)) > *buflen) return COAP_ERR_BUFFER_TOO_SMALL; optDelta = pkt->opts[i].num - running_delta; coap_option_nibble(optDelta, &delta); coap_option_nibble((uint32_t)pkt->opts[i].buf.len, &len); *p++ = (0xFF & (delta << 4 | len)); if (delta == 13) { *p++ = (optDelta - 13); } else if (delta == 14) { *p++ = ((optDelta-269) >> 8); *p++ = (0xFF & (optDelta-269)); } if (len == 13) { *p++ = (pkt->opts[i].buf.len - 13); } else if (len == 14) { *p++ = (pkt->opts[i].buf.len >> 8); *p++ = (0xFF & (pkt->opts[i].buf.len-269)); } memcpy(p, pkt->opts[i].buf.p, pkt->opts[i].buf.len); p += pkt->opts[i].buf.len; running_delta = pkt->opts[i].num; } opts_len = (p - buf) - 4; // number of bytes used by options if (pkt->payload.len > 0) { if (*buflen < 4 + 1 + pkt->payload.len + opts_len) return COAP_ERR_BUFFER_TOO_SMALL; buf[4 + opts_len] = 0xFF; // payload marker memcpy(buf+5 + opts_len, pkt->payload.p, pkt->payload.len); *buflen = opts_len + 5 + pkt->payload.len; } else *buflen = opts_len + 4; return 0; } void ICACHE_FLASH_ATTR coap_option_nibble(uint32_t value, uint8_t *nibble) { if (value<13) { *nibble = (0xFF & value); } else if (value<=0xFF+13) { *nibble = 13; } else if (value<=0xFFFF+269) { *nibble = 14; } } int ICACHE_FLASH_ATTR coap_make_response(coap_rw_buffer_t *scratch, coap_packet_t *pkt, const uint8_t *content, size_t content_len, uint8_t msgid_hi, uint8_t msgid_lo, const coap_buffer_t* tok, coap_responsecode_t rspcode, coap_content_type_t content_type) { pkt->hdr.ver = 0x01; pkt->hdr.t = COAP_TYPE_ACK; pkt->hdr.tkl = 0; pkt->hdr.code = rspcode; pkt->hdr.id[0] = msgid_hi; pkt->hdr.id[1] = msgid_lo; pkt->numopts = 1; // need token in response if (tok) { pkt->hdr.tkl = tok->len; pkt->tok = *tok; } // safe because 1 < MAXOPT pkt->opts[0].num = COAP_OPTION_CONTENT_FORMAT; pkt->opts[0].buf.p = scratch->p; if (scratch->len < 2) return COAP_ERR_BUFFER_TOO_SMALL; scratch->p[0] = ((uint16_t)content_type & 0xFF00) >> 8; scratch->p[1] = ((uint16_t)content_type & 0x00FF); pkt->opts[0].buf.len = 2; pkt->payload.p = content; pkt->payload.len = content_len; return 0; } // FIXME, if this looked in the table at the path before the method then // it could more easily return 405 errors int ICACHE_FLASH_ATTR coap_handle_req(coap_rw_buffer_t *scratch, const coap_packet_t *inpkt, coap_packet_t *outpkt) { const coap_option_t *opt; uint8_t count; int i; const coap_endpoint_t *ep = endpoints; while(NULL != ep->handler) { if (ep->method != inpkt->hdr.code) goto next; if (NULL != (opt = coap_findOptions(inpkt, COAP_OPTION_URI_PATH, &count))) { if (count != ep->path->count) goto next; for (i=0;i<count;i++) { if (opt[i].buf.len != strlen(ep->path->elems[i])) goto next; if (0 != memcmp(ep->path->elems[i], opt[i].buf.p, opt[i].buf.len)) goto next; } // match! return ep->handler(scratch, inpkt, outpkt, inpkt->hdr.id[0], inpkt->hdr.id[1]); } next: ep++; } coap_make_response(scratch, outpkt, NULL, 0, inpkt->hdr.id[0], inpkt->hdr.id[1], &inpkt->tok, COAP_RSPCODE_NOT_FOUND, COAP_CONTENTTYPE_NONE); return 0; } void coap_setup(void) { }
AccretionD/ESP8266_freertos_coap
app/user/coap.c
C
mit
12,020
module Softlayer module Container module Dns autoload :Domain, 'softlayer/container/dns/domain' end end end
zertico/softlayer
lib/softlayer/container/dns.rb
Ruby
mit
126
<aside class="main-sidebar"> <section class="sidebar"> <div class="user-panel"> <div class="pull-left image"> <img src="<?php echo base_url() ?>assets/img/user2-160x160.jpg" class="img-circle" alt="User Image"> </div> <div class="pull-left info"> <p>Alexander Pierce</p> <i class="fa fa-circle text-success"></i> Online </div> </div> <!-- sidebar menu: : style can be found in sidebar.less --> <ul class="sidebar-menu"> <li class="treeview"> <a href="#"> <i class="fa fa-users"></i> <span>Funcionarios</span> <i class="fa fa-angle-left pull-right"></i> </a> <ul class="treeview-menu"> <li><a href="<?php echo base_url()?>funcionarios/Index/registroFuncionarios"><i class="fa fa-circle-o text-aqua"></i> Registro Funcionarios</a></li> <li><a href="<?php echo base_url()?>funcionarios/Index/listadoFuncionarios"><i class="fa fa-circle-o text-aqua"></i> Listado Funcionarios</a></li> </ul> </li> <li class="treeview"> <a href="#"> <i class="fa fa-cogs"></i> <span>Cuentas de Usuarios</span> <i class="fa fa-angle-left pull-right"></i> </a> <ul class="treeview-menu"> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Registro Funcionarios</a></li> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Listado Funcionarios</a></li> </ul> </li> <li class="treeview"> <a href="#"> <i class="fa fa-graduation-cap" aria-hidden="true"></i> <span>Matrícula de Párvulos</span> <i class="fa fa-angle-left pull-right"></i> </a> <ul class="treeview-menu"> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Registro Funcionarios</a></li> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Listado Funcionarios</a></li> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Reporte Funcionarios</a></li> </ul> </li> <li class="treeview"> <a href="#"> <i class="fa fa-cubes" aria-hidden="true"></i> <span>Niveles Jardín</span> <i class="fa fa-angle-left pull-right"></i> </a> <ul class="treeview-menu"> <li><a href="<?php echo base_url() ?>niveles/Index/crearNivel"><i class="fa fa-circle-o text-aqua"></i> Registrar Niveles Jardín</a></li> <li><a href="<?php echo base_url() ?>niveles/Index/crearNivelAnual"><i class="fa fa-circle-o text-aqua"></i> Crear Niveles Anuales</a></li> <li><a href="<?php echo base_url() ?>niveles/Index/armarNivelAnual"><i class="fa fa-circle-o text-aqua"></i> Armar Niveles</a></li> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Listado Niveles</a></li> </ul> </li> <li class="treeview"> <a href="#"> <i class="fa fa-book" aria-hidden="true"></i> <span>Unidades de Contenido</span> <i class="fa fa-angle-left pull-right"></i> </a> <ul class="treeview-menu"> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Registro Funcionarios</a></li> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Listado Funcionarios</a></li> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Reporte Funcionarios</a></li> </ul> </li> <li class="treeview"> <a href="#"> <i class="fa fa-laptop" aria-hidden="true"></i> <span>Planific. Educadora</span> <i class="fa fa-angle-left pull-right"></i> </a> <ul class="treeview-menu"> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Registro Funcionarios</a></li> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Listado Funcionarios</a></li> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Reporte Funcionarios</a></li> </ul> </li> <li class="treeview"> <a href="#"> <i class="fa fa-bar-chart" aria-hidden="true"></i> <span>Reportes</span> <i class="fa fa-angle-left pull-right"></i> </a> <ul class="treeview-menu"> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Registro Funcionarios</a></li> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Listado Funcionarios</a></li> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Reporte Funcionarios</a></li> </ul> </li> <li class="treeview"> <a href="#"> <i class="fa fa-question-circle" aria-hidden="true"></i> <span>Ayuda</span> <i class="fa fa-angle-left pull-right"></i> </a> <ul class="treeview-menu"> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Registro Funcionarios</a></li> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Listado Funcionarios</a></li> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Reporte Funcionarios</a></li> </ul> </li> </ul> </section> </aside>
codenous/intranet_planEvalWeb
application/views/template/sidebar.php
PHP
mit
5,929
package com.agileEAP.workflow.definition; /** 活动类型 */ public enum ActivityType { /** 开始活动 */ //C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to .NET attributes: //[Remark("开始活动")] StartActivity(1), /** 人工活动 */ //C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to .NET attributes: //[Remark("人工活动")] ManualActivity(2), /** 路由活动 */ //C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to .NET attributes: //[Remark("路由活动")] RouterActivity(3), /** 子流程活动 */ //C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to .NET attributes: //[Remark("子流程活动")] SubflowActivity(4), /** 自动活动 */ //C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to .NET attributes: //[Remark("自动活动")] AutoActivity(5), /** 结束活动 */ //C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to .NET attributes: //[Remark("结束活动")] EndActivity(6), /** 处理活动 */ //C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to .NET attributes: //[Remark("处理活动")] ProcessActivity(7); private int intValue; private static java.util.HashMap<Integer, ActivityType> mappings; private synchronized static java.util.HashMap<Integer, ActivityType> getMappings() { if (mappings == null) { mappings = new java.util.HashMap<Integer, ActivityType>(); } return mappings; } private ActivityType(int value) { intValue = value; ActivityType.getMappings().put(value, this); } public int getValue() { return intValue; } public static ActivityType forValue(int value) { return getMappings().get(value); } }
AgileEAP/aglieEAP
agileEAP-workflow/src/main/java/com/agileEAP/workflow/definition/ActivityType.java
Java
mit
1,812
<?xml version="1.0" ?><!DOCTYPE TS><TS language="uk" version="2.0"> <defaumlcodec>UTF-8</defaumlcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About Menlocoin</source> <translation>Про Menlocoin</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;Menlocoin&lt;/b&gt; version</source> <translation>Версія &lt;b&gt;Menlocoin&apos;a&lt;b&gt;</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation> Це програмне забезпечення є експериментальним. Поширюється за ліцензією MIT/X11, додаткова інформація міститься у файлі COPYING, а також за адресою http://www.opensource.org/licenses/mit-license.php. Цей продукт включає в себе програмне забезпечення, розроблене в рамках проекту OpenSSL (http://www.openssl.org/), криптографічне програмне забезпечення, написане Еріком Янгом (eay@cryptsoft.com), та функції для роботи з UPnP, написані Томасом Бернардом.</translation> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation>Авторське право</translation> </message> <message> <location line="+0"/> <source>The Menlocoin developers</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Адресна книга</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>Двічі клікніть на адресу чи назву для їх зміни</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Створити нову адресу</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Копіювати виділену адресу в буфер обміну</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>&amp;Створити адресу</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your Menlocoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation>Це ваші адреси для отримання платежів. Ви можете давати різні адреси різним людям, таким чином маючи можливість відслідкувати хто конкретно і скільки вам заплатив.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation>&amp;Скопіювати адресу</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>Показати QR-&amp;Код</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a Menlocoin address</source> <translation>Підпишіть повідомлення щоб довести, що ви є власником цієї адреси</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>&amp;Підписати повідомлення</translation> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation>Вилучити вибрані адреси з переліку</translation> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation>Експортувати дані з поточної вкладки в файл</translation> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified Menlocoin address</source> <translation>Перевірте повідомлення для впевненості, що воно підписано вказаною Menlocoin-адресою</translation> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation>Перевірити повідомлення</translation> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Видалити</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your Menlocoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation>Скопіювати &amp;мітку</translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>&amp;Редагувати</translation> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation type="unfinished"/> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>Експортувати адресну книгу</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Файли відділені комами (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Помилка при експортуванні</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Неможливо записати у файл %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Назва</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Адреса</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(немає назви)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>Діалог введення паролю</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Введіть пароль</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Новий пароль</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Повторіть пароль</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Введіть новий пароль для гаманця.&lt;br/&gt;Будь ласка, використовуйте паролі що містять &lt;b&gt;як мінімум 10 випадкових символів&lt;/b&gt;, або &lt;b&gt;як мінімум 8 слів&lt;/b&gt;.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Зашифрувати гаманець</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Ця операція потребує пароль для розблокування гаманця.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Розблокувати гаманець</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Ця операція потребує пароль для дешифрування гаманця.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Дешифрувати гаманець</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Змінити пароль</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Ввести старий та новий паролі для гаманця.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Підтвердити шифрування гаманця</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR LITECOINS&lt;/b&gt;!</source> <translation>УВАГА: Якщо ви зашифруєте гаманець і забудете пароль, ви &lt;b&gt;ВТРАТИТЕ ВСІ СВОЇ БІТКОІНИ&lt;/b&gt;!</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Ви дійсно хочете зашифрувати свій гаманець?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Увага: Ввімкнено Caps Lock!</translation> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>Гаманець зашифровано</translation> </message> <message> <location line="-56"/> <source>Menlocoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your menlocoins from being stolen by malware infecting your computer.</source> <translation>Біткоін-клієнт буде закрито для завершення процесу шифрування. Пам&apos;ятайте, що шифрування гаманця не може повністю захистити ваші біткоіни від крадіжки, у випадку якщо ваш комп&apos;ютер буде інфіковано шкідливими програмами.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Не вдалося зашифрувати гаманець</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Виникла помилка під час шифрування гаманця. Ваш гаманець не було зашифровано.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>Введені паролі не співпадають.</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>Не вдалося розблокувати гаманець</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Введений пароль є невірним.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Не вдалося розшифрувати гаманець</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Пароль було успішно змінено.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation>&amp;Підписати повідомлення...</translation> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation>Синхронізація з мережею...</translation> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation>&amp;Огляд</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Показати загальний огляд гаманця</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>Транзакції</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Переглянути історію транзакцій</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>Редагувати список збережених адрес та міток</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>Показати список адрес для отримання платежів</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>&amp;Вихід</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Вийти</translation> </message> <message> <location line="+4"/> <source>Show information about Menlocoin</source> <translation>Показати інформацію про Menlocoin</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>&amp;Про Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Показати інформацію про Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Параметри...</translation> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Шифрування гаманця...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Резервне копіювання гаманця...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>Змінити парол&amp;ь...</translation> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation>Імпорт блоків з диску...</translation> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation type="unfinished"/> </message> <message> <location line="-347"/> <source>Send coins to a Menlocoin address</source> <translation>Відправити монети на вказану адресу</translation> </message> <message> <location line="+49"/> <source>Modify configuration options for Menlocoin</source> <translation>Редагувати параметри</translation> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation>Резервне копіювання гаманця в інше місце</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Змінити пароль, який використовується для шифрування гаманця</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation>Вікно зневадження</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Відкрити консоль зневадження і діагностики</translation> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation>Перевірити повідомлення...</translation> </message> <message> <location line="-165"/> <location line="+530"/> <source>Menlocoin</source> <translation>Menlocoin</translation> </message> <message> <location line="-530"/> <source>Wallet</source> <translation>Гаманець</translation> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>&amp;About Menlocoin</source> <translation>&amp;Про Menlocoin</translation> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>Показати / Приховати</translation> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation>Показує або приховує головне вікно</translation> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Sign messages with your Menlocoin addresses to prove you own them</source> <translation>Підтвердіть, що Ви є власником повідомлення підписавши його Вашою Menlocoin-адресою </translation> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified Menlocoin addresses</source> <translation>Перевірте повідомлення для впевненості, що воно підписано вказаною Menlocoin-адресою</translation> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;Файл</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>&amp;Налаштування</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>&amp;Довідка</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>Панель вкладок</translation> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation>[тестова мережа]</translation> </message> <message> <location line="+47"/> <source>Menlocoin client</source> <translation>Menlocoin-клієнт</translation> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to Menlocoin network</source> <translation><numerusform>%n активне з&apos;єднання з мережею</numerusform><numerusform>%n активні з&apos;єднання з мережею</numerusform><numerusform>%n активних з&apos;єднань з мережею</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation>Оброблено %1 блоків історії транзакцій.</translation> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Error</source> <translation>Помилка</translation> </message> <message> <location line="+3"/> <source>Warning</source> <translation>Увага</translation> </message> <message> <location line="+3"/> <source>Information</source> <translation>Інформація</translation> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>Синхронізовано</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>Синхронізується...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation>Підтвердити комісію</translation> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>Надіслані транзакції</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>Отримані перекази</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Дата: %1 Кількість: %2 Тип: %3 Адреса: %4 </translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation>Обробка URI</translation> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid Menlocoin address or malformed URI parameters.</source> <translation>Неможливо обробити URI! Це може бути викликано неправильною Menlocoin-адресою, чи невірними параметрами URI.</translation> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>&lt;b&gt;Зашифрований&lt;/b&gt; гаманець &lt;b&gt;розблоковано&lt;/b&gt;</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>&lt;b&gt;Зашифрований&lt;/b&gt; гаманець &lt;b&gt;заблоковано&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. Menlocoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation>Сповіщення мережі</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Редагувати адресу</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Мітка</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>Мітка, пов&apos;язана з цим записом адресної книги</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Адреса</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>Адреса, пов&apos;язана з цим записом адресної книги. Може бути змінено тільки для адреси відправника.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>Нова адреса для отримання</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Нова адреса для відправлення</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Редагувати адресу для отримання</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Редагувати адресу для відправлення</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>Введена адреса «%1» вже присутня в адресній книзі.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid Menlocoin address.</source> <translation>Введена адреса «%1» не є коректною адресою в мережі Menlocoin.</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Неможливо розблокувати гаманець.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Не вдалося згенерувати нові ключі.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>Menlocoin-Qt</source> <translation>Menlocoin-Qt</translation> </message> <message> <location line="-12"/> <source>version</source> <translation>версія</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Використання:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation>параметри командного рядка</translation> </message> <message> <location line="+4"/> <source>UI options</source> <translation>Параметри інтерфейсу</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>Встановлення мови, наприклад &quot;de_DE&quot; (типово: системна)</translation> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation>Запускати згорнутим</translation> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation>Показувати заставку під час запуску (типово: 1)</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Параметри</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>&amp;Головні</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Заплатити комісі&amp;ю</translation> </message> <message> <location line="+31"/> <source>Automatically start Menlocoin after logging in to the system.</source> <translation>Автоматично запускати гаманець при вході до системи.</translation> </message> <message> <location line="+3"/> <source>&amp;Start Menlocoin on system login</source> <translation>&amp;Запускати гаманець при вході в систему</translation> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation>Скинути всі параметри клієнта на типові.</translation> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation>Скинути параметри</translation> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation>&amp;Мережа</translation> </message> <message> <location line="+6"/> <source>Automatically open the Menlocoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Автоматично відкривати порт для клієнту біткоін на роутері. Працює лише якщо ваш роутер підтримує UPnP і ця функція увімкнена.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Відображення порту через &amp;UPnP</translation> </message> <message> <location line="+7"/> <source>Connect to the Menlocoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation>Підключатись до мережі Menlocoin через SOCKS-проксі (наприклад при використанні Tor).</translation> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation>Підключатись через &amp;SOCKS-проксі:</translation> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>&amp;IP проксі:</translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>IP-адреса проксі-сервера (наприклад 127.0.0.1)</translation> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>&amp;Порт:</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Порт проксі-сервера (наприклад 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>SOCKS версії:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>Версія SOCKS-проксі (наприклад 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>&amp;Вікно</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Показувати лише іконку в треї після згортання вікна.</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>Мінімізувати &amp;у трей</translation> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>Згортати замість закриття. Якщо ця опція включена, програма закриється лише після вибору відповідного пункту в меню.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>Згортати замість закритт&amp;я</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>&amp;Відображення</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>Мова інтерфейсу користувача:</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting Menlocoin.</source> <translation>Встановлює мову інтерфейсу. Зміни набудуть чинності після перезапуску Menlocoin.</translation> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>В&amp;имірювати монети в:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Виберіть одиницю вимірювання монет, яка буде відображатись в гаманці та при відправленні.</translation> </message> <message> <location line="+9"/> <source>Whether to show Menlocoin addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>&amp;Відображати адресу в списку транзакцій</translation> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;Гаразд</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;Скасувати</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation>&amp;Застосувати</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation>типово</translation> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation>Підтвердження скидання параметрів</translation> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation>Деякі параметри потребують перезапуск клієнта для набуття чинності.</translation> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation>Продовжувати?</translation> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation>Увага</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting Menlocoin.</source> <translation>Цей параметр набуде чинності після перезапуску Menlocoin.</translation> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>Невірно вказано адресу проксі.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Форма</translation> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Menlocoin network after a connection is established, but this process has not completed yet.</source> <translation>Показана інформація вже може бути застарілою. Ваш гаманець буде автоматично синхронізовано з мережею Menlocoin після встановлення підключення, але цей процес ще не завершено.</translation> </message> <message> <location line="-124"/> <source>Balance:</source> <translation>Баланс:</translation> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>Непідтверджені:</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>Гаманець</translation> </message> <message> <location line="+107"/> <source>Immature:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Недавні транзакції&lt;/b&gt;</translation> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation>Ваш поточний баланс</translation> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>Загальна сума всіх транзакцій, які ще не підтверджені, та до цих пір не враховуються в загальному балансі</translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation>не синхронізовано</translation> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start menlocoin: click-to-pay handler</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation>Діалог QR-коду</translation> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>Запросити Платіж</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>Кількість:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>Мітка:</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>Повідомлення:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>&amp;Зберегти як...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation>Помилка при кодуванні URI в QR-код.</translation> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation>Невірно введено кількість, будь ласка, перевірте.</translation> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>Кінцевий URI занадто довгий, спробуйте зменшити текст для мітки / повідомлення.</translation> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation>Зберегти QR-код</translation> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation>PNG-зображення (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>Назва клієнту</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+339"/> <source>N/A</source> <translation>Н/Д</translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation>Версія клієнту</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>&amp;Інформація</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>Використовується OpenSSL версії</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Network</source> <translation>Мережа</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>Кількість підключень</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation>В тестовій мережі</translation> </message> <message> <location line="+23"/> <source>Block chain</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Поточне число блоків</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Last block time</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>Відкрити</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation>Параметри командного рядка</translation> </message> <message> <location line="+7"/> <source>Show the Menlocoin-Qt help message to get a list with possible Menlocoin command-line options.</source> <translation>Показати довідку Menlocoin-Qt для отримання переліку можливих параметрів командного рядка.</translation> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation>Показати</translation> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>Консоль</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>Дата збирання</translation> </message> <message> <location line="-104"/> <source>Menlocoin - Debug window</source> <translation>Menlocoin - Вікно зневадження</translation> </message> <message> <location line="+25"/> <source>Menlocoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation>Файл звіту зневадження</translation> </message> <message> <location line="+7"/> <source>Open the Menlocoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Очистити консоль</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the Menlocoin RPC console.</source> <translation>Вітаємо у консолі Menlocoin RPC.</translation> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>Використовуйте стрілки вгору вниз для навігації по історії, і &lt;b&gt;Ctrl-L&lt;/b&gt; для очищення екрана.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Наберіть &lt;b&gt;help&lt;/b&gt; для перегляду доступних команд.</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+124"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Відправити</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>Відправити на декілька адрес</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>Дод&amp;ати одержувача</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>Видалити всі поля транзакції</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>Очистити &amp;все</translation> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>Баланс:</translation> </message> <message> <location line="+10"/> <source>123.456 BTC</source> <translation>123.456 BTC</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Підтвердити відправлення</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>&amp;Відправити</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; адресату %2 (%3)</translation> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Підтвердіть відправлення</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>Ви впевнені що хочете відправити %1?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation> і </translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation>Адреса отримувача невірна, будь ласка перепровірте.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>Кількість монет для відправлення повинна бути більшою 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>Кількість монет для відправлення перевищує ваш баланс.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>Сума перевищить ваш баланс, якщо комісія %1 буде додана до вашої транзакції.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Знайдено адресу що дублюється. Відправлення на кожну адресу дозволяється лише один раз на кожну операцію переказу.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation>Помилка: Не вдалося створити транзакцію!</translation> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Помилка: транзакцію було відхилено. Це може статись, якщо декілька монет з вашого гаманця вже використані, наприклад, якщо ви використовуєте одну копію гаманця (wallet.dat), а монети були використані з іншої копії, але не позначені як використані в цій.</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>Форма</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>&amp;Кількість:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>&amp;Отримувач:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation>Введіть мітку для цієї адреси для додавання її в адресну книгу</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>&amp;Мітка:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation>Вибрати адресу з адресної книги</translation> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Вставити адресу</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation>Видалити цього отримувача</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a Menlocoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Введіть адресу Menlocoin (наприклад Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>Підписи - Підпис / Перевірка повідомлення</translation> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation>&amp;Підписати повідомлення</translation> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Введіть адресу Menlocoin (наприклад Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation>Вибрати адресу з адресної книги</translation> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation>Вставити адресу</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>Введіть повідомлення, яке ви хочете підписати тут</translation> </message> <message> <location line="+7"/> <source>Signature</source> <translation>Підпис</translation> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation>Копіювати поточну сигнатуру до системного буферу обміну</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this Menlocoin address</source> <translation>Підпишіть повідомлення щоб довести, що ви є власником цієї адреси</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>&amp;Підписати повідомлення</translation> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation>Скинути всі поля підпису повідомлення</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Очистити &amp;все</translation> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation>Перевірити повідомлення</translation> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Введіть адресу Menlocoin (наприклад Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified Menlocoin address</source> <translation>Перевірте повідомлення для впевненості, що воно підписано вказаною Menlocoin-адресою</translation> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation>Перевірити повідомлення</translation> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation>Скинути всі поля перевірки повідомлення</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a Menlocoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Введіть адресу Menlocoin (наприклад Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>Натисніть кнопку «Підписати повідомлення», для отримання підпису</translation> </message> <message> <location line="+3"/> <source>Enter Menlocoin signature</source> <translation>Введіть сигнатуру Menlocoin</translation> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>Введена нечинна адреса.</translation> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>Будь ласка, перевірте адресу та спробуйте ще.</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>Не вдалося підписати повідомлення.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>Повідомлення підписано.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>Підпис не можливо декодувати.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>Будь ласка, перевірте підпис та спробуйте ще.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>Не вдалося перевірити повідомлення.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>Повідомлення перевірено.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The Menlocoin developers</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation>[тестова мережа]</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>Відкрити до %1</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation>%1/поза інтернетом</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/не підтверджено</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 підтверджень</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>Статус</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Дата</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Згенеровано</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>Відправник</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>Отримувач</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>label</source> <translation>Мітка</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Кредит</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>не прийнято</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Дебет</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Комісія за транзакцію</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Загальна сума</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Повідомлення</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Коментар</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>ID транзакції</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation>Після генерації монет, потрібно зачекати 120 блоків, перш ніж їх можна буде використати. Коли ви згенерували цей блок, його було відправлено в мережу для того, щоб він був доданий до ланцюжка блоків. Якщо ця процедура не вдасться, статус буде змінено на «не підтверджено» і ви не зможете потратити згенеровані монету. Таке може статись, якщо хтось інший згенерував блок на декілька секунд раніше.</translation> </message> <message> <location line="+7"/> <source>Debug information</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Транзакція</translation> </message> <message> <location line="+3"/> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Кількість</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>true</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>false</translation> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, ще не було успішно розіслано</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>невідомий</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Деталі транзакції</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Даний діалог показує детальну статистику по вибраній транзакції</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>Дата</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Тип</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Адреса</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Кількість</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>Відкрити до %1</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>Поза інтернетом (%1 підтверджень)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>Непідтверджено (%1 із %2 підтверджень)</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>Підтверджено (%1 підтверджень)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Цей блок не був отриманий жодними іншими вузлами і, ймовірно, не буде прийнятий!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Згенеровано, але не підтверджено</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>Отримано</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Отримано від</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Відправлено</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Відправлено собі</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Добуто</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(недоступно)</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Статус транзакції. Наведіть вказівник на це поле, щоб показати кількість підтверджень.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Дата і час, коли транзакцію було отримано.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Тип транзакції.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Адреса отримувача транзакції.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Сума, додана чи знята з балансу.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>Всі</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Сьогодні</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>На цьому тижні</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>На цьому місяці</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Минулого місяця</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Цього року</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Проміжок...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Отримані на</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Відправлені на</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Відправлені собі</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Добуті</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Інше</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Введіть адресу чи мітку для пошуку</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Мінімальна сума</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Скопіювати адресу</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Скопіювати мітку</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Копіювати кількість</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Редагувати мітку</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Показати деталі транзакції</translation> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation>Експортувати дані транзакцій</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Файли, розділені комою (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Підтверджені</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Дата</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Тип</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Мітка</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Адреса</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Кількість</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>Ідентифікатор</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Помилка експорту</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Неможливо записати у файл %1.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Діапазон від:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>до</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation>Відправити</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation>Експортувати дані з поточної вкладки в файл</translation> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation>Виникла помилка при спробі зберегти гаманець в новому місці.</translation> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation>Успішне створення резервної копії</translation> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation>Данні гаманця успішно збережено в новому місці призначення.</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>Menlocoin version</source> <translation>Версія</translation> </message> <message> <location line="+102"/> <source>Usage:</source> <translation>Використання:</translation> </message> <message> <location line="-29"/> <source>Send command to -server or menlocoind</source> <translation>Відправити команду серверу -server чи демону</translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>Список команд</translation> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation>Отримати довідку по команді</translation> </message> <message> <location line="+24"/> <source>Options:</source> <translation>Параметри:</translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: menlocoin.conf)</source> <translation>Вкажіть файл конфігурації (типово: menlocoin.conf)</translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: menlocoind.pid)</source> <translation>Вкажіть pid-файл (типово: menlocoind.pid)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Вкажіть робочий каталог</translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Встановити розмір кешу бази даних в мегабайтах (типово: 25)</translation> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 9333 or testnet: 19333)</source> <translation>Чекати на з&apos;єднання на &lt;port&gt; (типово: 9333 або тестова мережа: 19333)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Підтримувати не більше &lt;n&gt; зв&apos;язків з колегами (типово: 125)</translation> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Поріг відключення неправильно під&apos;єднаних пірів (типово: 100)</translation> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Максимальній розмір вхідного буферу на одне з&apos;єднання (типово: 86400)</translation> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 9332 or testnet: 19332)</source> <translation>Прослуховувати &lt;port&gt; для JSON-RPC-з&apos;єднань (типово: 9332 або тестова мережа: 19332)</translation> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation>Приймати команди із командного рядка та команди JSON-RPC</translation> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation>Запустити в фоновому режимі (як демон) та приймати команди</translation> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation>Використовувати тестову мережу</translation> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </message> <message> <location line="-80"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=menlocoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;Menlocoin Alert&quot; admin@foo.com </source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. Menlocoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Помилка: транзакцію було відхилено. Це може статись, якщо декілька монет з вашого гаманця вже використані, наприклад, якщо ви використовуєте одну копію гаманця (wallet.dat), а монети були використані з іншої копії, але не позначені як використані в цій.</translation> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>Увага: встановлено занадто велику комісію (-paytxfee). Комісія зніматиметься кожен раз коли ви проводитимете транзакції.</translation> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong Menlocoin will not work properly.</source> <translation>Увага: будь ласка, перевірте дату і час на своєму комп&apos;ютері. Якщо ваш годинник йде неправильно, Menlocoin може працювати некоректно.</translation> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation>Увага: помилка читання wallet.dat! Всі ключі прочитано коректно, але дані транзакцій чи записи адресної книги можуть бути пропущені, або пошкоджені.</translation> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation>Увага: файл wallet.dat пошкоджено, дані врятовано! Оригінальний wallet.dat збережено як wallet.{timestamp}.bak до %s; якщо Ваш баланс чи транзакції неправильні, Ви можете відновити їх з резервної копії. </translation> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation>Спроба відновити закриті ключі з пошкодженого wallet.dat</translation> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation>Підключитись лише до вказаного вузла</translation> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation>Помилка ініціалізації бази даних блоків</translation> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation>Помилка завантаження бази даних блоків</translation> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation>Помилка: Мало вільного місця на диску!</translation> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation>Помилка: Гаманець заблокований, неможливо створити транзакцію!</translation> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation>Помилка: системна помилка: </translation> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation>Скільки блоків перевіряти під час запуску (типово: 288, 0 = всі)</translation> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation type="unfinished"/> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation>Імпорт блоків з зовнішнього файлу blk000??.dat</translation> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Information</source> <translation>Інформація</translation> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation>Помилка в адресі -tor: «%s»</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>Максимальний буфер, &lt;n&gt;*1000 байт (типово: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Максимальній розмір вихідного буферу на одне з&apos;єднання, &lt;n&gt;*1000 байт (типово: 1000)</translation> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation>Виводити більше налагоджувальної інформації. Мається на увазі всі шнші -debug* параметри</translation> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation>Доповнювати налагоджувальний вивід відміткою часу</translation> </message> <message> <location line="+5"/> <source>SSL options: (see the Menlocoin Wiki for SSL setup instructions)</source> <translation>Параметри SSL: (див. Menlocoin Wiki для налаштування SSL)</translation> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation>Вибір версії socks-проксі для використання (4-5, типово: 5)</translation> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Відсилати налагоджувальну інформацію на консоль, а не у файл debug.log</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation>Відсилати налагоджувальну інформацію до налагоджувача</translation> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation>Встановити максимальний розмір блоку у байтах (типово: 250000)</translation> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>Встановити мінімальний розмір блоку у байтах (типово: 0)</translation> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Стискати файл debug.log під час старту клієнта (типово: 1 коли відсутутній параметр -debug)</translation> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Вказати тайм-аут підключення у мілісекундах (типово: 5000)</translation> </message> <message> <location line="+4"/> <source>System error: </source> <translation>Системна помилка: </translation> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>Намагатись використовувати UPnP для відображення порту, що прослуховується на роутері (default: 0)</translation> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Намагатись використовувати UPnP для відображення порту, що прослуховується на роутері (default: 1 when listening)</translation> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation>Ім&apos;я користувача для JSON-RPC-з&apos;єднань</translation> </message> <message> <location line="+4"/> <source>Warning</source> <translation>Попередження</translation> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>Увага: Поточна версія застаріла, необхідне оновлення!</translation> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation>wallet.dat пошкоджено, відновлення не вдалося</translation> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation>Пароль для JSON-RPC-з&apos;єднань</translation> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Дозволити JSON-RPC-з&apos;єднання з вказаної IP-адреси</translation> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Відправляти команди на вузол, запущений на &lt;ip&gt; (типово: 127.0.0.1)</translation> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation type="unfinished"/> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation>Модернізувати гаманець до останнього формату</translation> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Встановити розмір пулу ключів &lt;n&gt; (типово: 100)</translation> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Пересканувати ланцюжок блоків, в пошуку втрачених транзакцій</translation> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Використовувати OpenSSL (https) для JSON-RPC-з&apos;єднань</translation> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation>Файл сертифіката сервера (типово: server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Закритий ключ сервера (типово: server.pem)</translation> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Допустимі шифри (типово: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation> </message> <message> <location line="+165"/> <source>This help message</source> <translation>Дана довідка</translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Неможливо прив&apos;язати до порту %s на цьому комп&apos;ютері (bind returned error %d, %s)</translation> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation>Підключитись через SOCKS-проксі</translation> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Дозволити пошук в DNS для команд -addnode, -seednode та -connect</translation> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation>Завантаження адрес...</translation> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Помилка при завантаженні wallet.dat: Гаманець пошкоджено</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of Menlocoin</source> <translation>Помилка при завантаженні wallet.dat: Гаманець потребує новішої версії Біткоін-клієнта</translation> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart Menlocoin to complete</source> <translation>Потрібно перезаписати гаманець: перезапустіть Біткоін-клієнт для завершення</translation> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation>Помилка при завантаженні wallet.dat</translation> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Помилка в адресі проксі-сервера: «%s»</translation> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>Невідома мережа вказана в -onlynet: «%s»</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Помилка у величині комісії -paytxfee=&lt;amount&gt;: «%s»</translation> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>Некоректна кількість</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation>Недостатньо коштів</translation> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>Завантаження індексу блоків...</translation> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Додати вузол до підключення і лишити його відкритим</translation> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. Menlocoin is probably already running.</source> <translation>Неможливо прив&apos;язати до порту %s на цьому комп&apos;ютері. Можливо гаманець вже запущено.</translation> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation>Комісія за КБ</translation> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation>Завантаження гаманця...</translation> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation>Неможливо записати типову адресу</translation> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation>Сканування...</translation> </message> <message> <location line="-57"/> <source>Done loading</source> <translation>Завантаження завершене</translation> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation type="unfinished"/> </message> <message> <location line="-74"/> <source>Error</source> <translation>Помилка</translation> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation>Ви мусите встановити rpcpassword=&lt;password&gt; в файлі конфігурації: %s Якщо файл не існує, створіть його із правами тільки для читання власником (owner-readable-only).</translation> </message> </context> </TS>
iLoftis/Menlo-Coin
src/qt/locale/bitcoin_uk.ts
TypeScript
mit
123,486
package com.asayama.rps.simulator; public enum Hand { ROCK, PAPER, SCISSORS; }
kyoken74/rock-paper-scissors
src/main/java/com/asayama/rps/simulator/Hand.java
Java
mit
83
package foodtruck.linxup; import java.util.List; import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import org.joda.time.DateTime; import foodtruck.model.Location; /** * @author aviolette * @since 11/1/16 */ public class Trip { private Location start; private Location end; private DateTime startTime; private DateTime endTime; private List<Position> positions; private Trip(Builder builder) { this.start = builder.start; this.end = builder.end; this.startTime = builder.startTime; this.endTime = builder.endTime; this.positions = ImmutableList.copyOf(builder.positions); } public static Builder builder() { return new Builder(); } public static Builder builder(Trip instance) { return new Builder(instance); } public String getName() { return start.getShortenedName() + " to " + end.getShortenedName(); } public Location getStart() { return start; } public Location getEnd() { return end; } public DateTime getStartTime() { return startTime; } public DateTime getEndTime() { return endTime; } public List<Position> getPositions() { return positions; } @Override public String toString() { return MoreObjects.toStringHelper(this) // .add("start", start) // .add("end", end) .add("startTime", startTime) .add("endTime", endTime) .toString(); } public static class Builder { private Location start; private Location end; private DateTime startTime; private DateTime endTime; private List<Position> positions = Lists.newLinkedList(); public Builder() { } public Builder(Trip instance) { this.start = instance.start; this.end = instance.end; this.startTime = instance.startTime; this.endTime = instance.endTime; this.positions = instance.positions; } public Builder start(Location start) { this.start = start; return this; } public Builder end(Location end) { this.end = end; return this; } public Builder startTime(DateTime startTime) { this.startTime = startTime; return this; } public Builder endTime(DateTime endTime) { this.endTime = endTime; return this; } public Trip build() { return new Trip(this); } public DateTime getStartTime() { return startTime; } public DateTime getEndTime() { return endTime; } public Builder addPosition(Position position) { positions.add(position); return this; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("start", start.getShortenedName()) .add("end", end.getShortenedName()) // .add("start", start) // .add("end", end) .add("startTime", startTime) .add("endTime", endTime) .toString(); } } }
aviolette/foodtrucklocator
main/src/main/java/foodtruck/linxup/Trip.java
Java
mit
3,020
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_77) on Sun Aug 13 19:07:39 PKT 2017 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class com.hikmat30ce.workday.integrator.hr.generated.CompensationStepReferenceDataType (WorkdayIntegrator-HR 1.0.0 API)</title> <meta name="date" content="2017-08-13"> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class com.hikmat30ce.workday.integrator.hr.generated.CompensationStepReferenceDataType (WorkdayIntegrator-HR 1.0.0 API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../com/hikmat30ce/workday/integrator/hr/generated/CompensationStepReferenceDataType.html" title="class in com.hikmat30ce.workday.integrator.hr.generated">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?com/hikmat30ce/workday/integrator/hr/generated/class-use/CompensationStepReferenceDataType.html" target="_top">Frames</a></li> <li><a href="CompensationStepReferenceDataType.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class com.hikmat30ce.workday.integrator.hr.generated.CompensationStepReferenceDataType" class="title">Uses of Class<br>com.hikmat30ce.workday.integrator.hr.generated.CompensationStepReferenceDataType</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../../com/hikmat30ce/workday/integrator/hr/generated/CompensationStepReferenceDataType.html" title="class in com.hikmat30ce.workday.integrator.hr.generated">CompensationStepReferenceDataType</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#com.hikmat30ce.workday.integrator.hr.generated">com.hikmat30ce.workday.integrator.hr.generated</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="com.hikmat30ce.workday.integrator.hr.generated"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../com/hikmat30ce/workday/integrator/hr/generated/CompensationStepReferenceDataType.html" title="class in com.hikmat30ce.workday.integrator.hr.generated">CompensationStepReferenceDataType</a> in <a href="../../../../../../../com/hikmat30ce/workday/integrator/hr/generated/package-summary.html">com.hikmat30ce.workday.integrator.hr.generated</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing fields, and an explanation"> <caption><span>Fields in <a href="../../../../../../../com/hikmat30ce/workday/integrator/hr/generated/package-summary.html">com.hikmat30ce.workday.integrator.hr.generated</a> declared as <a href="../../../../../../../com/hikmat30ce/workday/integrator/hr/generated/CompensationStepReferenceDataType.html" title="class in com.hikmat30ce.workday.integrator.hr.generated">CompensationStepReferenceDataType</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>protected <a href="../../../../../../../com/hikmat30ce/workday/integrator/hr/generated/CompensationStepReferenceDataType.html" title="class in com.hikmat30ce.workday.integrator.hr.generated">CompensationStepReferenceDataType</a></code></td> <td class="colLast"><span class="typeNameLabel">CompensationDetailDataType.</span><code><span class="memberNameLink"><a href="../../../../../../../com/hikmat30ce/workday/integrator/hr/generated/CompensationDetailDataType.html#compensationStepReference">compensationStepReference</a></span></code>&nbsp;</td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../../com/hikmat30ce/workday/integrator/hr/generated/package-summary.html">com.hikmat30ce.workday.integrator.hr.generated</a> that return <a href="../../../../../../../com/hikmat30ce/workday/integrator/hr/generated/CompensationStepReferenceDataType.html" title="class in com.hikmat30ce.workday.integrator.hr.generated">CompensationStepReferenceDataType</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../../com/hikmat30ce/workday/integrator/hr/generated/CompensationStepReferenceDataType.html" title="class in com.hikmat30ce.workday.integrator.hr.generated">CompensationStepReferenceDataType</a></code></td> <td class="colLast"><span class="typeNameLabel">ObjectFactory.</span><code><span class="memberNameLink"><a href="../../../../../../../com/hikmat30ce/workday/integrator/hr/generated/ObjectFactory.html#createCompensationStepReferenceDataType--">createCompensationStepReferenceDataType</a></span>()</code> <div class="block">Create an instance of <a href="../../../../../../../com/hikmat30ce/workday/integrator/hr/generated/CompensationStepReferenceDataType.html" title="class in com.hikmat30ce.workday.integrator.hr.generated"><code>CompensationStepReferenceDataType</code></a></div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../../../com/hikmat30ce/workday/integrator/hr/generated/CompensationStepReferenceDataType.html" title="class in com.hikmat30ce.workday.integrator.hr.generated">CompensationStepReferenceDataType</a></code></td> <td class="colLast"><span class="typeNameLabel">CompensationDetailDataType.</span><code><span class="memberNameLink"><a href="../../../../../../../com/hikmat30ce/workday/integrator/hr/generated/CompensationDetailDataType.html#getCompensationStepReference--">getCompensationStepReference</a></span>()</code> <div class="block">Gets the value of the compensationStepReference property.</div> </td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../../com/hikmat30ce/workday/integrator/hr/generated/package-summary.html">com.hikmat30ce.workday.integrator.hr.generated</a> with parameters of type <a href="../../../../../../../com/hikmat30ce/workday/integrator/hr/generated/CompensationStepReferenceDataType.html" title="class in com.hikmat30ce.workday.integrator.hr.generated">CompensationStepReferenceDataType</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><span class="typeNameLabel">CompensationDetailDataType.</span><code><span class="memberNameLink"><a href="../../../../../../../com/hikmat30ce/workday/integrator/hr/generated/CompensationDetailDataType.html#setCompensationStepReference-com.hikmat30ce.workday.integrator.hr.generated.CompensationStepReferenceDataType-">setCompensationStepReference</a></span>(<a href="../../../../../../../com/hikmat30ce/workday/integrator/hr/generated/CompensationStepReferenceDataType.html" title="class in com.hikmat30ce.workday.integrator.hr.generated">CompensationStepReferenceDataType</a>&nbsp;value)</code> <div class="block">Sets the value of the compensationStepReference property.</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../com/hikmat30ce/workday/integrator/hr/generated/CompensationStepReferenceDataType.html" title="class in com.hikmat30ce.workday.integrator.hr.generated">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?com/hikmat30ce/workday/integrator/hr/generated/class-use/CompensationStepReferenceDataType.html" target="_top">Frames</a></li> <li><a href="CompensationStepReferenceDataType.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2017 <a href="http://www.spring.io">Pivotal Software, Inc.</a>. All rights reserved.</small></p> </body> </html>
hikmat30ce/WorkdayIntegrator-HR
docs/com/hikmat30ce/workday/integrator/hr/generated/class-use/CompensationStepReferenceDataType.html
HTML
mit
11,646
/** * Copyright (c) 2015, Alexander Orzechowski. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /** * Currently in beta stage. Changes can and will be made to the core mechanic * making this not backwards compatible. * * Github: https://github.com/Need4Speed402/tessellator */ Tessellator.TextureDummy = function (ready){ this.super(null); if (ready){ this.setReady(); }; }; Tessellator.extend(Tessellator.TextureDummy, Tessellator.Texture); Tessellator.TextureDummy.prototype.configure = Tessellator.EMPTY_FUNC; Tessellator.TextureDummy.prototype.bind = Tessellator.EMPTY_FUNC;
Need4Speed402/tessellator
src/textures/TextureDummy.js
JavaScript
mit
1,646
 <!DOCTYPE HTML> <!-- Solid State by HTML5 UP html5up.net | @ajlkn Free for personal and commercial use under the CCA 3.0 license (html5up.net/license) --> <html> <head> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-72755780-1"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-72755780-1'); </script> <script src="/assets/js/redirectNow.js"></script> <title>Richard Kingston - Progressive Web App</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <!--[if lte IE 8]><script src="/assets/js/ie/html5shiv.js"></script><![endif]--> <link rel="stylesheet" href="/assets/sass/main.css" /> <link rel="stylesheet" href="/assets/css/override.css" /> <!--[if lte IE 9]><link rel="stylesheet" href="/assets/sass/ie9.css" /><![endif]--> <!--[if lte IE 8]><link rel="stylesheet" href="/assets/sass/ie8.css" /><![endif]--> </head> <body> <!-- Page Wrapper --> <div id="page-wrapper"> <!-- Header --> <header id="header"> <h1><a href="/">Richard Kingston</a></h1> <nav> <a href="#menu">Menu</a> </nav> </header> <!-- Menu --> <nav id="menu"> <div class="inner"> <h2>Menu</h2> <ul class="links"> <li><a href="/posts">Archive</a></li> <li><a href="/tags">Tags</a></li> <li><a href="/about">About Me</a></li> </ul> <a href="#" class="close">Close</a> </div> </nav> <section id="banner"> <div class="inner"> <h2>Progressive Web App</h2> </div> </section> <!-- Main --> <section id="wrapper"> <section class="wrapper style2"> <div class="inner"> <div> <a href="/posts/council-knows-whats-appnin"> <h3>Council knows what&#x27;s &#x27;appnin&#x27;</h3> <p>There&#x27;s nothing quite like delivering customer value that&#x27;s fit for the future, scalable and miles ahead of the curve ;-)</p> </a> <p><em>Posted on 15 September 2017</em></p> </div> <hr> <nav> <ul class="actions"> </ul> </nav> </div> </section> <section class="wrapper alt style3"> <div class="inner"> <a role="button" href="/tags/Income-Management" class="button small ">Income Management (30)</a> <a role="button" href="/tags/Local-Digital-Fund" class="button small ">Local Digital Fund (24)</a> <a role="button" href="/tags/IMS-Discovery" class="button small ">IMS Discovery (21)</a> <a role="button" href="/tags/Innovation-Group" class="button small ">Innovation Group (14)</a> <a role="button" href="/tags/DigiDesk" class="button small ">DigiDesk (8)</a> <a role="button" href="/tags/DigiBook" class="button small ">DigiBook (5)</a> <a role="button" href="/tags/DigiMeet" class="button small ">DigiMeet (4)</a> <a role="button" href="/tags/IMS-Alpha" class="button small ">IMS Alpha (2)</a> <a role="button" href="/tags/Work-Life-Balance" class="button small ">Work Life Balance (2)</a> <a role="button" href="/tags/TechTown" class="button small ">TechTown (2)</a> <a role="button" href="/tags/Digital-First" class="button small ">Digital First (2)</a> <a role="button" href="/tags/Requestry" class="button small ">Requestry (2)</a> <a role="button" href="/tags/Barnsley-Makers" class="button small ">Barnsley Makers (1)</a> <a role="button" href="/tags/Code-Club" class="button small ">Code Club (1)</a> <a role="button" href="/tags/Barnsley-Council" class="button small ">Barnsley Council (1)</a> <a role="button" href="/tags/Progressive-Web-App" class="button small special">Progressive Web App (1)</a> <a role="button" href="/tags/DigiSafe" class="button small ">DigiSafe (1)</a> <a role="button" href="/tags/Digital-Barnsley" class="button small ">Digital Barnsley (1)</a> </div> </section> </section> <!-- Footer --> <footer id="footer"> <div class="inner"> <section> <h2>Feeds</h2> <ul class="actions"> <li><a href="/feed.rss" class="button small"><i class="fa fa-rss"></i> RSS Feed</a></li> <li><a href="/feed.atom" class="button small"><i class="fa fa-rss"></i> Atom Feed</a></li> </ul> </section> <section> </section> <ul class="copyright"> <li>Copyright © 2020</li> <li>Design: <a href="http://html5up.net">HTML5 UP</a></li> <li><a href="https://wyam.io">Generated by Wyam</a></li> </ul> </div> </footer> </div> <!-- Scripts --> <script src="/assets/js/skel.min.js"></script> <script src="/assets/js/jquery.min.js"></script> <script src="/assets/js/jquery.scrollex.min.js"></script> <script src="/assets/js/util.js"></script> <!--[if lte IE 8]><script src="/assets/js/ie/respond.min.js"></script><![endif]--> <script src="/assets/js/main.js"></script> <script src="/assets/js/redirectNow.js"></script> <script type="text/javascript">redirectNow();</script> </body> </html>
kingstonrichard/kingstonrichard.github.io
tags/Progressive-Web-App.html
HTML
mit
5,561
#include "Extensions.hpp" #include "Extensions.inl" #include <Math/Rect.hpp> #include <Math/Vector.hpp> #include <Script/ScriptExtensions.hpp> #include <SFML/Graphics/CircleShape.hpp> #include <angelscript.h> #include <cassert> namespace { void create_CircleShape(void* memory) { new(memory)sf::CircleShape(); } void create_CircleShape_rad(float radius, unsigned int count, void* memory) { new(memory)sf::CircleShape(radius, count); } bool Reg() { Script::ScriptExtensions::AddExtension([](asIScriptEngine* eng) { int r = 0; r = eng->SetDefaultNamespace("Shapes"); assert(r >= 0); r = eng->RegisterObjectType("Circle", sizeof(sf::CircleShape), asOBJ_VALUE | asGetTypeTraits<sf::CircleShape>()); assert(r >= 0); r = eng->RegisterObjectBehaviour("Circle", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(create_CircleShape), asCALL_CDECL_OBJLAST); assert(r >= 0); r = eng->RegisterObjectBehaviour("Circle", asBEHAVE_CONSTRUCT, "void f(float,uint=30)", asFUNCTION(create_CircleShape_rad), asCALL_CDECL_OBJLAST); assert(r >= 0); r = eng->RegisterObjectMethod("Circle", "void set_PointCount(uint)", asMETHOD(sf::CircleShape, setPointCount), asCALL_THISCALL); assert(r >= 0); r = eng->RegisterObjectMethod("Circle", "float get_Radius()", asMETHOD(sf::CircleShape, getRadius), asCALL_THISCALL); assert(r >= 0); r = eng->RegisterObjectMethod("Circle", "void set_Radius(float)", asMETHOD(sf::CircleShape, setRadius), asCALL_THISCALL); assert(r >= 0); Script::SFML::registerShape<sf::CircleShape>("Circle", eng); r = eng->SetDefaultNamespace(""); assert(r >= 0); }, 6); return true; } } bool Script::SFML::Extensions::CircleShape = Reg();
ace13/LD31
Source/Script/SFML/CircleShape.cpp
C++
mit
1,833
'use strict'; module.exports = function(sequelize, DataTypes) { var Student = sequelize.define('Student', { name: DataTypes.STRING, timeReq: DataTypes.INTEGER, }, { classMethods: { associate: function() { } } }); return Student; };
troops2devs/minutes
models/student.js
JavaScript
mit
268
module Culqi VERSION = '1.2.8' end
augustosamame/culqiruby
lib/culqi/version.rb
Ruby
mit
37
<!DOCTYPE html> <html lang=""> <head> <title><%= webpackConfig.metadata.title %></title> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="<%= webpackConfig.metadata.title %>"> <link rel="manifest" href="/assets/manifest.json"> <meta name="msapplication-TileColor" content="#00bcd4"> <meta name="msapplication-TileImage" content="/assets/icon/ms-icon-144x144.png"> <meta name="theme-color" content="#00bcd4"> <!-- end favicon --> <!-- base url --> <base href="<%= webpackConfig.metadata.baseUrl %>"> </head> <body > <app> Loading... </app> <!-- Google Analytics: change UA-71073175-1 to be your site's ID --> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-71073175-1', 'auto'); ga('send', 'pageview'); </script> <% if (webpackConfig.metadata.ENV === 'development') { %> <!-- Webpack Dev Server reload --> <script src="http://<%= webpackConfig.metadata.host %>:<%= webpackConfig.metadata.port %>/webpack-dev-server.js"></script> <% } %> </body> </html>
andbet39/Angular2Sensor
src/index.html
HTML
mit
1,457
#include <CImageLibI.h> #include <CImageColorDefP.h> #include <cstring> bool CImageColorDef:: getRGB(const std::string &name, double *r, double *g, double *b) { int ri, gi, bi; if (! getRGBI(name, &ri, &gi, &bi)) return false; double rgb_scale = 1.0/255.0; *r = ri*rgb_scale; *g = gi*rgb_scale; *b = bi*rgb_scale; return true; } bool CImageColorDef:: getRGBI(const std::string &name, int *r, int *g, int *b) { int i; std::string lname = CStrUtil::toLower(name); const char *name1 = lname.c_str(); for (i = 0; color_def_data[i].name != 0; ++i) if (strcmp(color_def_data[i].name, name1) == 0) break; if (color_def_data[i].name == 0) return false; *r = color_def_data[i].r; *g = color_def_data[i].g; *b = color_def_data[i].b; return true; }
colinw7/CImageLib
src/CImageColorDef.cpp
C++
mit
801
const {xObjectForm} = require('./xObjectForm'); exports._getPathOptions = function _getPathOptions(options = {}, originX, originY) { this.current = this.current || {}; const colorspace = options.colorspace || this.options.colorspace; const colorName = options.colorName; const pathOptions = { originX, originY, font: this._getFont(options), size: options.size || this.current.defaultFontSize, charSpace: options.charSpace || 0, underline: false, color: this._transformColor(options.color, {colorspace:colorspace, colorName:options.colorName}), colorspace, colorName, colorArray: [], lineCap: this._lineCap(), lineJoin: this._lineJoin(), miterLimit: 1.414, width: 2, align: options.align }; if (options.opacity == void(0) || isNaN(options.opacity)) { options.opacity = 1; } else { options.opacity = (options.opacity < 0) ? 0 : (options.opacity > 1) ? 1 : options.opacity; } pathOptions.opacity = options.opacity; const extGStates = this._createExtGStates(options.opacity); pathOptions.strokeGsId = extGStates.stroke; pathOptions.fillGsId = extGStates.fill; if (options.size || options.fontSize) { const size = options.size || options.fontSize; if (!isNaN(size)) { pathOptions.size = (size <= 0) ? 1 : size; } } if (options.width || options.lineWidth) { const width = options.width || options.lineWidth; if (!isNaN(width)) { pathOptions.width = (width <= 0) ? 1 : width; } } const colorOpts = {colorspace:colorspace, wantColorModel:true, colorName: options.colorName}; if (options.stroke) { pathOptions.strokeModel = this._transformColor(options.stroke, colorOpts); pathOptions.stroke = pathOptions.strokeModel.color; } if (options.fill) { pathOptions.fillModel = this._transformColor(options.fill, colorOpts); pathOptions.fill = pathOptions.fillModel.color; } pathOptions.colorModel = this._transformColor((options.color || options.colour), colorOpts); pathOptions.color = pathOptions.colorModel.color; pathOptions.colorspace = pathOptions.colorModel.colorspace; // rotation if (options.rotation !== void(0)) { const rotation = parseFloat(options.rotation); pathOptions.rotation = rotation; pathOptions.rotationOrigin = options.rotationOrigin || null; } // skew if (options.skewX !== void(0)) { pathOptions.skewX = options.skewX; } if (options.skewY != void(0)) { pathOptions.skewY = options.skewY; } // Page 127 of PDF 1.7 specification pathOptions.dash = (Array.isArray(options.dash)) ? options.dash : []; pathOptions.dashPhase = (!isNaN(options.dashPhase)) ? options.dashPhase : 0; if (pathOptions.dash[0] == 0 && pathOptions.dash[1] == 0) { pathOptions.dash = []; // no dash, solid unbroken line pathOptions.dashPhase = 0; } // Page 125-126 of PDF 1.7 specification if (options.lineJoin !== void(0)) { pathOptions.lineJoin = this._lineJoin(options.lineJoin); } if (options.lineCap !== void(0)) { pathOptions.lineCap = this._lineCap(options.lineCap); } if (options.miterLimit !== void(0)) { if (!isNaN(options.miterLimit)) { pathOptions.miterLimit = options.miterLimit; } } return pathOptions; }; exports._getDistance = function _getDistance(coordA, coordB) { const disX = Math.abs(coordB[0] - coordA[0]); const disY = Math.abs(coordB[1] - coordB[1]); const distance = Math.sqrt(((disX * disX) + (disY * disY))); return distance; }; exports._getTransformParams = getTransformParams; function getTransformParams(inAngle, x, y, offsetX, offsetY) { const theta = toRadians(inAngle); const cosTheta = Math.cos(theta); const sinTheta = Math.sin(theta); const nx = (cosTheta * -offsetX) + (sinTheta * -offsetY); const ny = (cosTheta * -offsetY) - (sinTheta * -offsetX); return [cosTheta, -sinTheta, sinTheta, cosTheta, x - nx, y - ny]; } exports._setRotationContext = function _setRotationTransform(context, x, y, options) { const deltaY = (options.deltaY) ? options.deltaY : 0; if (options.rotation === undefined || options.rotation === 0) { context.cm(1, 0, 0, 1, x, y-deltaY); // no rotation } else { let rotationOrigin; if (!hasRotation(options)) { rotationOrigin = [options.originX, options.originY]; // supply default } else { if (options.useGivenCoords) { rotationOrigin = options.rotationOrigin; } else { const orig = this._calibrateCoordinate(options.rotationOrigin[0], options.rotationOrigin[1]); rotationOrigin = [orig.nx, orig.ny]; } } const rm = getTransformParams( // rotation matrix options.rotation, rotationOrigin[0], rotationOrigin[1], x - rotationOrigin[0], y - rotationOrigin[1] - deltaY ); context.cm(rm[0], rm[1], rm[2], rm[3], rm[4], rm[5]); } }; function hasRotation(options) { return options.rotationOrigin && Array.isArray(options.rotationOrigin) && options.rotationOrigin.length === 2; } function toRadians(angle) { return 2 * Math.PI * ((angle % 360) / 360); } function getSkewTransform(skewXAngle= 0 , skewYAngle = 0) { const alpha = toRadians(skewXAngle); const beta = toRadians(skewYAngle); const tanAlpha = Math.tan(alpha); const tanBeta = Math.tan(beta); return [1, tanAlpha, tanBeta, 1, 0, 0]; } exports._setSkewContext = function _setSkewTransform(context, options) { if (options.skewX || options.skewY) { const sm = getSkewTransform(options.skewX, options.skewY); context.cm(sm[0], sm[1], sm[2], sm[3], sm[4], sm[5]); } }; exports._setScalingTransform = function _setScalingTransform(context, options) { if (options.ratio) { context.cm(options.ratio[0], 0, 0, options.ratio[1], 0, 0); } }; exports._drawObject = function _drawObject(self, x, y, width, height, options, callback) { let xObject = options.xObject; // allows caller to supply existing form object if (!xObject) { self.pauseContext(); xObject = new xObjectForm(self.writer, width, height); const xObjectCtx = xObject.getContentContext(); xObjectCtx.q(); callback(xObjectCtx, xObject); xObjectCtx.Q(); xObject.end(); self.resumeContext(); } const context = self.pageContext; context.q(); self._setRotationContext(context, x, y, options); self._setSkewContext(context, options); self._setScalingTransform(context, options); context .doXObject(xObject) .Q(); }; exports._lineCap = function _lineCap(type) { const round = 1; let cap = round; if (type) { const capStyle = ['butt', 'round', 'square']; const capType = capStyle.indexOf(type); cap = (capType !== -1) ? capType : round; } return cap; }; exports._lineJoin = function _lineJoin(type) { const round = 1; let join = round; if (type) { const joinStyle = ['miter', 'round', 'bevel']; const joinType = joinStyle.indexOf(type); join = (joinType !== -1) ? joinType : round; } return join; };
chunyenHuang/hummusRecipe
lib/vector.helper.js
JavaScript
mit
7,549
SUBROUTINE WFN1_AD_DSYGST( ITYPE, UPLO, N, A, LDA, B, LDB, INFO ) USE WFN1_AD1 IMPLICIT NONE #include "blas/double/intf_wfn1_ad_dsymm.fh" #include "blas/double/intf_wfn1_ad_dsyr2.fh" #include "blas/double/intf_wfn1_ad_dsyr2k.fh" #include "blas/double/intf_wfn1_ad_dtrmm.fh" #include "blas/double/intf_wfn1_ad_dtrsm.fh" #include "lapack/double/intf_wfn1_ad_dsygs2.fh" * * -- LAPACK routine (version 3.3.1) -- * -- LAPACK is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * -- April 2011 -- * * .. Scalar Arguments .. CHARACTER UPLO INTEGER INFO, ITYPE, LDA, LDB, N * .. * .. Array Arguments .. TYPE(WFN1_AD_DBLE) :: A( LDA, * ), B( LDB, * ) * .. * * Purpose * ======= * * DSYGST reduces a real symmetric-definite generalized eigenproblem * to standard form. * * If ITYPE = 1, the problem is A*x = lambda*B*x, * and A is overwritten by inv(U**T)*A*inv(U) or inv(L)*A*inv(L**T) * * If ITYPE = 2 or 3, the problem is A*B*x = lambda*x or * B*A*x = lambda*x, and A is overwritten by U*A*U**T or L**T*A*L. * * B must have been previously factorized as U**T*U or L*L**T by DPOTRF. * * Arguments * ========= * * ITYPE (input) INTEGER * = 1: compute inv(U**T)*A*inv(U) or inv(L)*A*inv(L**T); * = 2 or 3: compute U*A*U**T or L**T*A*L. * * UPLO (input) CHARACTER*1 * = 'U': Upper triangle of A is stored and B is factored as * U**T*U; * = 'L': Lower triangle of A is stored and B is factored as * L*L**T. * * N (input) INTEGER * The order of the matrices A and B. N >= 0. * * A (input/output) DOUBLE PRECISION array, dimension (LDA,N) * On entry, the symmetric matrix A. If UPLO = 'U', the leading * N-by-N upper triangular part of A contains the upper * triangular part of the matrix A, and the strictly lower * triangular part of A is not referenced. If UPLO = 'L', the * leading N-by-N lower triangular part of A contains the lower * triangular part of the matrix A, and the strictly upper * triangular part of A is not referenced. * * On exit, if INFO = 0, the transformed matrix, stored in the * same format as A. * * LDA (input) INTEGER * The leading dimension of the array A. LDA >= max(1,N). * * B (input) DOUBLE PRECISION array, dimension (LDB,N) * The triangular factor from the Cholesky factorization of B, * as returned by DPOTRF. * * LDB (input) INTEGER * The leading dimension of the array B. LDB >= max(1,N). * * INFO (output) INTEGER * = 0: successful exit * < 0: if INFO = -i, the i-th argument had an illegal value * * ===================================================================== * * .. Parameters .. TYPE(WFN1_AD_DBLE) :: ONE, HALF c PARAMETER ( ONE = 1.0D0, HALF = 0.5D0 ) * .. * .. Local Scalars .. LOGICAL UPPER INTEGER K, KB, NB * .. * .. External Subroutines .. EXTERNAL XERBLA * .. * .. Intrinsic Functions .. c INTRINSIC MAX, MIN * .. * .. External Functions .. LOGICAL LSAME INTEGER ILAENV EXTERNAL LSAME, ILAENV * .. * .. Executable Statements .. * * Test the input parameters. * ONE = 1.0d0 HALF = 0.5d0 INFO = 0 UPPER = LSAME( UPLO, 'U' ) IF( ITYPE.LT.1 .OR. ITYPE.GT.3 ) THEN INFO = -1 ELSE IF( .NOT.UPPER .AND. .NOT.LSAME( UPLO, 'L' ) ) THEN INFO = -2 ELSE IF( N.LT.0 ) THEN INFO = -3 ELSE IF( LDA.LT.MAX( 1, N ) ) THEN INFO = -5 ELSE IF( LDB.LT.MAX( 1, N ) ) THEN INFO = -7 END IF IF( INFO.NE.0 ) THEN CALL XERBLA( 'DSYGST', -INFO ) RETURN END IF * * Quick return if possible * IF( N.EQ.0 ) $ RETURN * * Determine the block size for this environment. * NB = ILAENV( 1, 'DSYGST', UPLO, N, -1, -1, -1 ) * IF( NB.LE.1 .OR. NB.GE.N ) THEN * * Use unblocked code * CALL WFN1_AD_DSYGS2( ITYPE, UPLO, N, A, LDA, B, LDB, INFO ) ELSE * * Use blocked code * IF( ITYPE.EQ.1 ) THEN IF( UPPER ) THEN * * Compute inv(U**T)*A*inv(U) * DO 10 K = 1, N, NB KB = MIN( N-K+1, NB ) * * Update the upper triangle of A(k:n,k:n) * CALL WFN1_AD_DSYGS2( ITYPE, UPLO, KB, A( K, K ), LDA, $ B( K, K ), LDB, INFO ) IF( K+KB.LE.N ) THEN CALL WFN1_AD_DTRSM( 'Left', UPLO, 'Transpose', $ 'Non-unit', KB, N-K-KB+1, ONE, B( K, K ), LDB, $ A( K, K+KB ), LDA ) CALL WFN1_AD_DSYMM( 'Left', UPLO, KB, N-K-KB+1, $ -HALF, A( K, K ), LDA, B( K, K+KB ), LDB, ONE, $ A( K, K+KB ), LDA ) CALL WFN1_AD_DSYR2K( UPLO, 'Transpose', N-K-KB+1, $ KB, -ONE, A( K, K+KB ), LDA, B( K, K+KB ), $ LDB, ONE, A( K+KB, K+KB ), LDA ) CALL WFN1_AD_DSYMM( 'Left', UPLO, KB, N-K-KB+1, $ -HALF, A( K, K ), LDA, B( K, K+KB ), LDB, ONE, $ A( K, K+KB ), LDA ) CALL WFN1_AD_DTRSM( 'Right', UPLO, 'No transpose', $ 'Non-unit', KB, N-K-KB+1, ONE, $ B( K+KB, K+KB ), LDB, A( K, K+KB ), LDA ) END IF 10 CONTINUE ELSE * * Compute inv(L)*A*inv(L**T) * DO 20 K = 1, N, NB KB = MIN( N-K+1, NB ) * * Update the lower triangle of A(k:n,k:n) * CALL WFN1_AD_DSYGS2( ITYPE, UPLO, KB, A( K, K ), LDA, $ B( K, K ), LDB, INFO ) IF( K+KB.LE.N ) THEN CALL WFN1_AD_DTRSM( 'Right', UPLO, 'Transpose', $ 'Non-unit', N-K-KB+1, KB, ONE, B( K, K ), LDB, $ A( K+KB, K ), LDA ) CALL WFN1_AD_DSYMM( 'Right', UPLO, N-K-KB+1, KB, $ -HALF, A( K, K ), LDA, B( K+KB, K ), LDB, ONE, $ A( K+KB, K ), LDA ) CALL WFN1_AD_DSYR2K( UPLO, 'No transpose', $ N-K-KB+1, KB, -ONE, A( K+KB, K ), LDA, $ B( K+KB, K ), LDB, ONE, A( K+KB, K+KB ), LDA ) CALL WFN1_AD_DSYMM( 'Right', UPLO, N-K-KB+1, KB, $ -HALF, A( K, K ), LDA, B( K+KB, K ), LDB, ONE, $ A( K+KB, K ), LDA ) CALL WFN1_AD_DTRSM( 'Left', UPLO, 'No transpose', $ 'Non-unit', N-K-KB+1, KB, ONE, $ B( K+KB, K+KB ), LDB, A( K+KB, K ), LDA ) END IF 20 CONTINUE END IF ELSE IF( UPPER ) THEN * * Compute U*A*U**T * DO 30 K = 1, N, NB KB = MIN( N-K+1, NB ) * * Update the upper triangle of A(1:k+kb-1,1:k+kb-1) * CALL WFN1_AD_DTRMM( 'Left', UPLO, 'No transpose', $ 'Non-unit', K-1, KB, ONE, B, LDB, $ A( 1, K ), LDA ) CALL WFN1_AD_DSYMM( 'Right', UPLO, K-1, KB, HALF, $ A( K, K ), LDA, B( 1, K ), LDB, ONE, $ A( 1, K ), LDA ) CALL WFN1_AD_DSYR2K( UPLO, 'No transpose', K-1, KB, $ ONE, A( 1, K ), LDA, B( 1, K ), LDB, ONE, $ A, LDA ) CALL WFN1_AD_DSYMM( 'Right', UPLO, K-1, KB, HALF, $ A( K, K ), LDA, B( 1, K ), LDB, ONE, $ A( 1, K ), LDA ) CALL WFN1_AD_DTRMM( 'Right', UPLO, 'Transpose', $ 'Non-unit', K-1, KB, ONE, B( K, K ), LDB, $ A( 1, K ), LDA ) CALL WFN1_AD_DSYGS2( ITYPE, UPLO, KB, A( K, K ), LDA, $ B( K, K ), LDB, INFO ) 30 CONTINUE ELSE * * Compute L**T*A*L * DO 40 K = 1, N, NB KB = MIN( N-K+1, NB ) * * Update the lower triangle of A(1:k+kb-1,1:k+kb-1) * CALL WFN1_AD_DTRMM( 'Right', UPLO, 'No transpose', $ 'Non-unit', KB, K-1, ONE, B, LDB, $ A( K, 1 ), LDA ) CALL WFN1_AD_DSYMM( 'Left', UPLO, KB, K-1, HALF, $ A( K, K ), LDA, B( K, 1 ), LDB, ONE, $ A( K, 1 ), LDA ) CALL WFN1_AD_DSYR2K( UPLO, 'Transpose', K-1, KB, ONE, $ A( K, 1 ), LDA, B( K, 1 ), LDB, ONE, A, LDA ) CALL WFN1_AD_DSYMM( 'Left', UPLO, KB, K-1, HALF, $ A( K, K ), LDA, B( K, 1 ), LDB, ONE, $ A( K, 1 ), LDA ) CALL WFN1_AD_DTRMM( 'Left', UPLO, 'Transpose', $ 'Non-unit', KB, K-1, ONE, B( K, K ), LDB, $ A( K, 1 ), LDA ) CALL WFN1_AD_DSYGS2( ITYPE, UPLO, KB, A( K, K ), LDA, $ B( K, K ), LDB, INFO ) 40 CONTINUE END IF END IF END IF RETURN * * End of DSYGST * END
rangsimanketkaew/NWChem
src/rdmft/recycling/wfn1/lapack/double/wfn1_ad_dsygst.f
FORTRAN
mit
9,696
<?php namespace WebEd\Base\ThemesManagement\Actions; use WebEd\Base\Actions\AbstractAction; class EnableThemeAction extends AbstractAction { /** * @param $alias * @return array */ public function run($alias) { do_action(WEBED_THEME_BEFORE_ENABLE, $alias); $theme = get_theme_information($alias); if (!$theme) { return $this->error('Plugin not exists'); } $checkRelatedModules = check_module_require($theme); if ($checkRelatedModules['error']) { $messages = []; foreach ($checkRelatedModules['messages'] as $message) { $messages[] = $message; } return $this->error($messages); } themes_management()->enableTheme($alias); do_action(WEBED_THEME_ENABLED, $alias); modules_management()->refreshComposerAutoload(); return $this->success('Your theme has been enabled'); } }
sgsoft-studio/themes-management
src/Actions/EnableThemeAction.php
PHP
mit
971
// // NFAnalogClockView+Extension.h // NFAnalogClock // // Created by Neil Francis Hipona on 12/1/16. // Copyright © 2016 Neil Francis Hipona. All rights reserved. // #import "NFAnalogClockView.h" @interface NFAnalogClockView (Extension) - (void)startTime; - (void)stopTime; - (NFTime *)updateClock; @end
nferocious76/NFAnalogClock
NFAnalogClock/NFAnalogClockView+Extension.h
C
mit
315
___ <strong>Javascript</strong> <h3>Arrays</h3> --- ##Summary We can access an array's items using **indices**. Arrays have a variety of methods to utilize. ##Discussion ```javascript var myArray = ["Alex", "Andrew", "James"]; myArray[0]; // this will return "Alex" // let's assign a new value to "James" myArray[2] = "Woodstock"; ``` We also covered a lot of **methods** that each array has. Here are the methods we used. - **pop()** - removes and returns the the *last* item in the array. - **push()** - adds an item to the end of the array. - **shift()** - removes the *first* item in an array. - **unshift()** - adds an item to the *start* of the array. - **reverse()** - reverses the order of an array. - **sort()** - sorts an array by alpha-numerics, based on the first character read. ## References Your references may be placed here. Please place them in an unordered list and add a quick summary of each. - <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/array">MDN: Arrays</a>
ga-chicago/ga-chicago.github.io
darth-vader/01_front_end_fundamentals/javascript_arrays.md
Markdown
mit
1,040
--- layout: default --- <div class="posts"> {% for post in site.posts %} <article class="post"> {% if post.icon %} <div style="float: left; padding-right: 20px; margin-top: 10px"> <img style="" src="{{post.icon}}" width="50" height="50"/> </div> {% endif %} <a class="post-link" href="{{ site.baseurl }}{{ post.url }}"><h1>{{ post.title }}</h1></a> <p class="post-meta post-meta-date">{{ post.date | date: "%b %d %Y" }}</p> <div class="entry"> {{ post.excerpt }} </div> <a href="{{ site.baseurl }}{{ post.url }}" class="read-more">Read More</a> </article> {% endfor %} </div>
mbarralo/mbarralo.github.io
index.html
HTML
mit
662
// Copyright 2014 The Gogs Authors. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package models import ( "bufio" "bytes" "fmt" "html" "html/template" "io" "io/ioutil" "os" "os/exec" "strings" "github.com/Unknwon/com" "github.com/sergi/go-diff/diffmatchpatch" "golang.org/x/net/html/charset" "golang.org/x/text/transform" "github.com/gogits/git-module" "github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/log" "github.com/gogits/gogs/modules/process" ) type DiffLineType uint8 const ( DIFF_LINE_PLAIN DiffLineType = iota + 1 DIFF_LINE_ADD DIFF_LINE_DEL DIFF_LINE_SECTION ) type DiffFileType uint8 const ( DIFF_FILE_ADD DiffFileType = iota + 1 DIFF_FILE_CHANGE DIFF_FILE_DEL DIFF_FILE_RENAME ) type DiffLine struct { LeftIdx int RightIdx int Type DiffLineType Content string } func (d *DiffLine) GetType() int { return int(d.Type) } type DiffSection struct { Name string Lines []*DiffLine } var ( addedCodePrefix = []byte("<span class=\"added-code\">") removedCodePrefix = []byte("<span class=\"removed-code\">") codeTagSuffix = []byte("</span>") ) func diffToHTML(diffs []diffmatchpatch.Diff, lineType DiffLineType) template.HTML { var buf bytes.Buffer for i := range diffs { if diffs[i].Type == diffmatchpatch.DiffInsert && lineType == DIFF_LINE_ADD { buf.Write(addedCodePrefix) buf.WriteString(html.EscapeString(diffs[i].Text)) buf.Write(codeTagSuffix) } else if diffs[i].Type == diffmatchpatch.DiffDelete && lineType == DIFF_LINE_DEL { buf.Write(removedCodePrefix) buf.WriteString(html.EscapeString(diffs[i].Text)) buf.Write(codeTagSuffix) } else if diffs[i].Type == diffmatchpatch.DiffEqual { buf.WriteString(html.EscapeString(diffs[i].Text)) } } return template.HTML(buf.Bytes()) } // get an specific line by type (add or del) and file line number func (diffSection *DiffSection) GetLine(lineType DiffLineType, idx int) *DiffLine { difference := 0 for _, diffLine := range diffSection.Lines { if diffLine.Type == DIFF_LINE_PLAIN { // get the difference of line numbers between ADD and DEL versions difference = diffLine.RightIdx - diffLine.LeftIdx continue } if lineType == DIFF_LINE_DEL { if diffLine.RightIdx == 0 && diffLine.LeftIdx == idx-difference { return diffLine } } else if lineType == DIFF_LINE_ADD { if diffLine.LeftIdx == 0 && diffLine.RightIdx == idx+difference { return diffLine } } } return nil } // computes inline diff for the given line func (diffSection *DiffSection) GetComputedInlineDiffFor(diffLine *DiffLine) template.HTML { var compareDiffLine *DiffLine var diff1, diff2 string getDefaultReturn := func() template.HTML { return template.HTML(html.EscapeString(diffLine.Content[1:])) } // just compute diff for adds and removes if diffLine.Type != DIFF_LINE_ADD && diffLine.Type != DIFF_LINE_DEL { return getDefaultReturn() } // try to find equivalent diff line. ignore, otherwise if diffLine.Type == DIFF_LINE_ADD { compareDiffLine = diffSection.GetLine(DIFF_LINE_DEL, diffLine.RightIdx) if compareDiffLine == nil { return getDefaultReturn() } diff1 = compareDiffLine.Content diff2 = diffLine.Content } else { compareDiffLine = diffSection.GetLine(DIFF_LINE_ADD, diffLine.LeftIdx) if compareDiffLine == nil { return getDefaultReturn() } diff1 = diffLine.Content diff2 = compareDiffLine.Content } dmp := diffmatchpatch.New() diffRecord := dmp.DiffMain(diff1[1:], diff2[1:], true) diffRecord = dmp.DiffCleanupSemantic(diffRecord) return diffToHTML(diffRecord, diffLine.Type) } type DiffFile struct { Name string OldName string Index int Addition, Deletion int Type DiffFileType IsCreated bool IsDeleted bool IsBin bool IsRenamed bool Sections []*DiffSection } func (diffFile *DiffFile) GetType() int { return int(diffFile.Type) } type Diff struct { TotalAddition, TotalDeletion int Files []*DiffFile } func (diff *Diff) NumFiles() int { return len(diff.Files) } const DIFF_HEAD = "diff --git " func ParsePatch(maxlines int, reader io.Reader) (*Diff, error) { var ( diff = &Diff{Files: make([]*DiffFile, 0)} curFile *DiffFile curSection = &DiffSection{ Lines: make([]*DiffLine, 0, 10), } leftLine, rightLine int lineCount int ) input := bufio.NewReader(reader) isEOF := false for { if isEOF { break } line, err := input.ReadString('\n') if err != nil { if err == io.EOF { isEOF = true } else { return nil, fmt.Errorf("ReadString: %v", err) } } if len(line) > 0 && line[len(line)-1] == '\n' { // Remove line break. line = line[:len(line)-1] } if strings.HasPrefix(line, "+++ ") || strings.HasPrefix(line, "--- ") { continue } else if len(line) == 0 { continue } lineCount++ // Diff data too large, we only show the first about maxlines lines if lineCount >= maxlines { log.Warn("Diff data too large") io.Copy(ioutil.Discard, reader) diff.Files = nil return diff, nil } switch { case line[0] == ' ': diffLine := &DiffLine{Type: DIFF_LINE_PLAIN, Content: line, LeftIdx: leftLine, RightIdx: rightLine} leftLine++ rightLine++ curSection.Lines = append(curSection.Lines, diffLine) continue case line[0] == '@': curSection = &DiffSection{} curFile.Sections = append(curFile.Sections, curSection) ss := strings.Split(line, "@@") diffLine := &DiffLine{Type: DIFF_LINE_SECTION, Content: line} curSection.Lines = append(curSection.Lines, diffLine) // Parse line number. ranges := strings.Split(ss[1][1:], " ") leftLine, _ = com.StrTo(strings.Split(ranges[0], ",")[0][1:]).Int() if len(ranges) > 1 { rightLine, _ = com.StrTo(strings.Split(ranges[1], ",")[0]).Int() } else { log.Warn("Parse line number failed: %v", line) rightLine = leftLine } continue case line[0] == '+': curFile.Addition++ diff.TotalAddition++ diffLine := &DiffLine{Type: DIFF_LINE_ADD, Content: line, RightIdx: rightLine} rightLine++ curSection.Lines = append(curSection.Lines, diffLine) continue case line[0] == '-': curFile.Deletion++ diff.TotalDeletion++ diffLine := &DiffLine{Type: DIFF_LINE_DEL, Content: line, LeftIdx: leftLine} if leftLine > 0 { leftLine++ } curSection.Lines = append(curSection.Lines, diffLine) case strings.HasPrefix(line, "Binary"): curFile.IsBin = true continue } // Get new file. if strings.HasPrefix(line, DIFF_HEAD) { middle := -1 // Note: In case file name is surrounded by double quotes (it happens only in git-shell). // e.g. diff --git "a/xxx" "b/xxx" hasQuote := line[len(DIFF_HEAD)] == '"' if hasQuote { middle = strings.Index(line, ` "b/`) } else { middle = strings.Index(line, " b/") } beg := len(DIFF_HEAD) a := line[beg+2 : middle] b := line[middle+3:] if hasQuote { a = string(git.UnescapeChars([]byte(a[1 : len(a)-1]))) b = string(git.UnescapeChars([]byte(b[1 : len(b)-1]))) } curFile = &DiffFile{ Name: a, Index: len(diff.Files) + 1, Type: DIFF_FILE_CHANGE, Sections: make([]*DiffSection, 0, 10), } diff.Files = append(diff.Files, curFile) // Check file diff type. for { line, err := input.ReadString('\n') if err != nil { if err == io.EOF { isEOF = true } else { return nil, fmt.Errorf("ReadString: %v", err) } } switch { case strings.HasPrefix(line, "new file"): curFile.Type = DIFF_FILE_ADD curFile.IsCreated = true case strings.HasPrefix(line, "deleted"): curFile.Type = DIFF_FILE_DEL curFile.IsDeleted = true case strings.HasPrefix(line, "index"): curFile.Type = DIFF_FILE_CHANGE case strings.HasPrefix(line, "similarity index 100%"): curFile.Type = DIFF_FILE_RENAME curFile.IsRenamed = true curFile.OldName = curFile.Name curFile.Name = b } if curFile.Type > 0 { break } } } } // FIXME: detect encoding while parsing. var buf bytes.Buffer for _, f := range diff.Files { buf.Reset() for _, sec := range f.Sections { for _, l := range sec.Lines { buf.WriteString(l.Content) buf.WriteString("\n") } } charsetLabel, err := base.DetectEncoding(buf.Bytes()) if charsetLabel != "UTF-8" && err == nil { encoding, _ := charset.Lookup(charsetLabel) if encoding != nil { d := encoding.NewDecoder() for _, sec := range f.Sections { for _, l := range sec.Lines { if c, _, err := transform.String(d, l.Content); err == nil { l.Content = c } } } } } } return diff, nil } func GetDiffRange(repoPath, beforeCommitID string, afterCommitID string, maxlines int) (*Diff, error) { repo, err := git.OpenRepository(repoPath) if err != nil { return nil, err } commit, err := repo.GetCommit(afterCommitID) if err != nil { return nil, err } var cmd *exec.Cmd // if "after" commit given if len(beforeCommitID) == 0 { // First commit of repository. if commit.ParentCount() == 0 { cmd = exec.Command("git", "show", afterCommitID) } else { c, _ := commit.Parent(0) cmd = exec.Command("git", "diff", "-M", c.ID.String(), afterCommitID) } } else { cmd = exec.Command("git", "diff", "-M", beforeCommitID, afterCommitID) } cmd.Dir = repoPath cmd.Stderr = os.Stderr stdout, err := cmd.StdoutPipe() if err != nil { return nil, fmt.Errorf("StdoutPipe: %v", err) } if err = cmd.Start(); err != nil { return nil, fmt.Errorf("Start: %v", err) } pid := process.Add(fmt.Sprintf("GetDiffRange (%s)", repoPath), cmd) defer process.Remove(pid) diff, err := ParsePatch(maxlines, stdout) if err != nil { return nil, fmt.Errorf("ParsePatch: %v", err) } if err = cmd.Wait(); err != nil { return nil, fmt.Errorf("Wait: %v", err) } return diff, nil } func GetDiffCommit(repoPath, commitId string, maxlines int) (*Diff, error) { return GetDiffRange(repoPath, "", commitId, maxlines) }
svcavallar/gogs
models/git_diff.go
GO
mit
10,244
--- layout: post date: 2017-09-30 title: "Jorge Manuel THE PEI Sleeveless Sweep/Brush Train Aline/Princess" category: Jorge Manuel tags: [Jorge Manuel ,Jorge Manuel,Aline/Princess ,Jewel,Sweep/Brush Train,Sleeveless] --- ### Jorge Manuel THE PEI Just **$379.99** ### Sleeveless Sweep/Brush Train Aline/Princess <table><tr><td>BRANDS</td><td>Jorge Manuel</td></tr><tr><td>Silhouette</td><td>Aline/Princess </td></tr><tr><td>Neckline</td><td>Jewel</td></tr><tr><td>Hemline/Train</td><td>Sweep/Brush Train</td></tr><tr><td>Sleeve</td><td>Sleeveless</td></tr></table> <a href="https://www.readybrides.com/en/jorge-manuel-/35789-jorge-manuel-the-pei.html"><img src="//img.readybrides.com/75049/jorge-manuel-the-pei.jpg" alt="Jorge Manuel THE PEI" style="width:100%;" /></a> <!-- break --> Buy it: [https://www.readybrides.com/en/jorge-manuel-/35789-jorge-manuel-the-pei.html](https://www.readybrides.com/en/jorge-manuel-/35789-jorge-manuel-the-pei.html)
novstylessee/novstylessee.github.io
_posts/2017-09-30-Jorge-Manuel-THE-PEI-Sleeveless-SweepBrush-Train-AlinePrincess.md
Markdown
mit
955
require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') describe Admin::PreferencesController do dataset :users it "should allow you to view your preferences" do user = login_as(:non_admin) get :edit response.should be_success assigned_user = assigns(:user) assigned_user.should == user assigned_user.object_id.should_not == user.object_id assigned_user.email.should == 'non_admin@example.com' end it "should allow you to save your preferences" do login_as :non_admin put :update, :user => { :password => '', :password_confirmation => '', :email => 'updated@gmail.com' } user = users(:non_admin) response.should redirect_to(admin_pages_path) flash[:notice].should match(/preferences.*?updated/i) user.email.should == 'updated@gmail.com' end it "should not allow you to update your login through the preferences page" do login_as :non_admin put :update, 'user' => { :login => 'superman' } response.should be_success flash[:error].should match(/bad form data/i) end it "should allow you to change your password" do login_as :non_admin put :update, { :user => { :password => 'funtimes', :password_confirmation => 'funtimes' } } user = users(:non_admin) user.password.should == user.sha1('funtimes') rails_log.should_not match(/"password"=>"funtimes"/) rails_log.should_not match(/"password_confirmation"=>"funtimes"/) end end
dosire/dosire
spec/controllers/admin/preferences_controller_spec.rb
Ruby
mit
1,463
--- title: 不是你难行的 date: 17/11/2021 --- 〈申命记〉第30章一开篇,主就告诉以色列百姓,如果他们悔改,转离恶行,就会发生什么事。上帝所赐予的是多么美好的应许啊! `阅读申30:1–10。尽管经文是在说如果他们不顺服会发生什么事,但上帝依然给了他们怎样的应许?这事对我们了解上帝的恩典有何启示?` 听到这般应许,当然倍感安慰。但这话的重点并非是说,即使他们违背了上帝的吩咐也没关系。上帝给人的绝不是廉价的恩典。祂所显明的是给人的爱,因此,人也当敬爱祂来作为回应,透过顺从祂的吩咐来表现出对祂的爱。 `阅读申30:11–14。上帝对他们说了什么?经文中有哪些基本的应许?你能想到新约中还有哪些经文表达了同样的应许?` 从优美的语言和严密的逻辑来看这个应许,主并没有让他们做什么难以达成的事。对他们来说,上帝的吩咐既不难理解,也不神秘,更不会因离他们太远而无法得到。它并不在天上,需要别人替他们取下来;也不在海外,需要别人过海去拿。主所说的是:「这话却离你甚近,就在你口中,在你心里,使你可以遵行。」(申30:14)也就是说,你对它足够了解,所以能够说出来,它就在你心里,所以你知道你必须去做。总之,你没有任何借口不顺从。「祂的一切吩咐都具有成全之能。」(怀爱伦,《基督比喻实训》, 第333页) 事实上,使徒保罗在探讨基督里的救赎时引用了这里的某些经文;他将它们作为因信称义的范例(参见罗10:6-10)。 紧接着这些经文之后,上帝吩咐以色列民作出选择,是生还是死,是福还是祸。如果他们因着恩典凭着信心选择了生命,那么他们就会得到生命。 今天其实也是一样,不是吗?
Adventech/sabbath-school-lessons
src/zh/2021-04/08/05.md
Markdown
mit
1,963
using System; using Pulse.FS; namespace Pulse.UI { public sealed class UiWpdLeafsAccessor : IUiLeafsAccessor { private readonly WpdArchiveListing _listing; private readonly WpdEntry[] _leafs; private readonly bool? _conversion; public UiNodeType Type { get { return UiNodeType.DataTable; } } public UiWpdLeafsAccessor(WpdArchiveListing listing, bool? conversion, params WpdEntry[] leafs) { _listing = listing; _leafs = leafs; _conversion = conversion; } public void Extract(IUiExtractionTarget target) { using (UiWpdExtractor extractor = new UiWpdExtractor(_listing, _leafs, _conversion, target)) extractor.Extract(); } public void Inject(IUiInjectionSource source, UiInjectionManager manager) { using (UiWpdInjector injector = new UiWpdInjector(_listing, _leafs, _conversion, source)) injector.Inject(manager); } } }
kidaa/Pulse
Pulse.UI/Windows/Main/Dockables/GameFileCommander/UiTree/Accessors/UiWpdLeafsAccessor.cs
C#
mit
1,061
import * as React from 'react'; import { DocumentCard } from './DocumentCard'; import { DocumentCardTitle } from './DocumentCardTitle'; import { DocumentCardPreview } from './DocumentCardPreview'; import { DocumentCardLocation } from './DocumentCardLocation'; import { DocumentCardActivity } from './DocumentCardActivity'; import { DocumentCardActions } from './DocumentCardActions'; import { PersonaInitialsColor } from '../../Persona'; import { ImageFit } from '../../Image'; import { IButtonProps } from '../../Button'; export interface IDocumentCard { } export interface IDocumentCardProps extends React.Props<DocumentCard> { /** * Optional callback to access the IDocumentCard interface. Use this instead of ref for accessing * the public methods and properties of the component. */ componentRef?: (component: IDocumentCard) => void; /** * The type of DocumentCard to display. * @default DocumentCardType.normal */ type?: DocumentCardType; /** * Function to call when the card is clicked or keyboard Enter/Space is pushed. */ onClick?: (ev?: React.SyntheticEvent<HTMLElement>) => void; /** * A URL to navigate to when the card is clicked. If a function has also been provided, * it will be used instead of the URL. */ onClickHref?: string; /** * Optional class for document card. */ className?: string; /** * Hex color value of the line below the card, which should correspond to the document type. * This should only be supplied when using the 'compact' card layout. */ accentColor?: string; } export enum DocumentCardType { /** * Standard DocumentCard. */ normal = 0, /** * Compact layout. Displays the preview beside the details, rather than above. */ compact = 1 } export interface IDocumentCardPreviewProps extends React.Props<DocumentCardPreview> { /** * One or more preview images to display. */ previewImages: IDocumentCardPreviewImage[]; /** * The function return string that will describe the number of overflow documents. * such as (overflowCount: number) => `+${ overflowCount } more`, */ getOverflowDocumentCountText?: (overflowCount: number) => string; } export interface IDocumentCardPreviewImage { /** * File name for the document this preview represents. */ name?: string; /** * URL to view the file. */ url?: string; /** * Path to the preview image. */ previewImageSrc?: string; /** * Deprecated at v1.3.6, to be removed at >= v2.0.0. * @deprecated */ errorImageSrc?: string; /** * Path to the icon associated with this document type. */ iconSrc?: string; /** * If provided, forces the preview image to be this width. */ width?: number; /** * If provided, forces the preview image to be this height. */ height?: number; /** * Used to determine how to size the image to fit the dimensions of the component. * If both dimensions are provided, then the image is fit using ImageFit.scale, otherwise ImageFit.none is used. */ imageFit?: ImageFit; /** * Hex color value of the line below the preview, which should correspond to the document type. */ accentColor?: string; } export interface IDocumentCardTitleProps extends React.Props<DocumentCardTitle> { /** * Title text. If the card represents more than one document, this should be the title of one document and a "+X" string. For example, a collection of four documents would have a string of "Document.docx +3". */ title: string; /** * Whether we truncate the title to fit within the box. May have a performance impact. * @defaultvalue true */ shouldTruncate?: boolean; } export interface IDocumentCardLocationProps extends React.Props<DocumentCardLocation> { /** * Text for the location of the document. */ location: string; /** * URL to navigate to for this location. */ locationHref?: string; /** * Function to call when the location is clicked. */ onClick?: (ev?: React.MouseEvent<HTMLElement>) => void; /** * Aria label for the link to the document location. */ ariaLabel?: string; } export interface IDocumentCardActivityProps extends React.Props<DocumentCardActivity> { /** * Describes the activity that has taken place, such as "Created Feb 23, 2016". */ activity: string; /** * One or more people who are involved in this activity. */ people: IDocumentCardActivityPerson[]; } export interface IDocumentCardActivityPerson { /** * The name of the person. */ name: string; /** * Path to the profile photo of the person. */ profileImageSrc: string; /** * The user's initials to display in the profile photo area when there is no image. */ initials?: string; /** * The background color when the user's initials are displayed. * @defaultvalue PersonaInitialsColor.blue */ initialsColor?: PersonaInitialsColor; } export interface IDocumentCardActionsProps extends React.Props<DocumentCardActions> { /** * The actions available for this document. */ actions: IButtonProps[]; /** * The number of views this document has received. */ views?: Number; }
SpatialMap/SpatialMapDev
node_modules/office-ui-fabric-react/src/components/DocumentCard/DocumentCard.Props.ts
TypeScript
mit
5,213
// // Created by paysonl on 16-10-20. // #include <vector> using std::vector; #include <iostream> #include <cassert> int min3(int a, int b, int c); int minSubSum(const vector<int>& a); int minSubRec(const vector<int>& a, int left, int right); int main() { vector<int> v{-2, -1, -2, 3, -4}; assert(minSubSum(v) == -6); } int minSubSum(const vector<int>& a) { return minSubRec(a, 0, a.size() - 1); } int minSubRec(const vector<int>& a, int left, int right) { if (left == right) if (a[left] < 0) return a[left]; else return 0; int mid = (left + right) / 2; int minLeftSum = minSubRec(a, left, mid); int minRightSum = minSubRec(a, mid + 1, right); int minLeftBorderSum = 0, leftBorderSum = 0; for (int i = mid; i >= left; --i) { leftBorderSum += a[i]; if (leftBorderSum < minLeftBorderSum) minLeftBorderSum = leftBorderSum; } int minRightBorderSum = 0, rightBorderSum = 0; for (int i = mid + 1; i <= right; ++i) { rightBorderSum += a[i]; if (rightBorderSum < minRightBorderSum) minRightBorderSum = rightBorderSum; } return min3(minLeftSum, minRightSum, minLeftBorderSum + minRightBorderSum); } int min3(int a, int b, int c) { int min2 = a < b ? a : b; return min2 < c ? min2 : c; }
frostRed/Exercises
DS_a_Algo_in_CPP/ch2/2-17-a.cpp
C++
mit
1,349
<?php /** * Created by PhpStorm. * User: Jan * Date: 17.03.2015 * Time: 17:03 */ namespace AppBundle\Repository; use Doctrine\ORM\EntityRepository; class ThreadRepository extends EntityRepository { public function findAllOrderedByLastModifiedDate($category_id) { $repository = $this->getEntityManager() ->getRepository('AppBundle:Thread'); $query = $repository->createQueryBuilder('t') ->where("t.category = :id") ->setParameter('id', $category_id) ->orderBy('t.last_modified_date', 'desc') ->getQuery(); return $query; } public function findAllPostsOrderedById($thread_id) { $repository = $this->getEntityManager() ->getRepository('AppBundle:Post'); $query = $repository->createQueryBuilder('p') ->where("p.thread = :id") ->setParameter('id', $thread_id) ->getQuery(); return $query; } }
mueller-jan/symfony-forum
src/AppBundle/Repository/ThreadRepository.php
PHP
mit
978
--- layout: post title: yesterday date: 2011-10-24 07:54 comments: false categories: [poems] --- i remember yesterday as if it were yesterday. and the day before that as if it were the day before yesterday. but the moment i remember any day before the day before yesterday as if it were yesterday, i forget the day that was yesterday.
thisduck/nothing
_posts/poems/2011-10-24-yesterday.markdown
Markdown
mit
346
# User info wrapper object import logging class User(object): """ Wrapper object around an entry in users.json. Behaves like a read-only dictionary if asked, but adds some useful logic to decouple the front end from the JSON structure. """ _NAME_KEYS = ["display_name", "real_name"] _DEFAULT_IMAGE_KEY = "image_512" def __init__(self, raw_data): self._raw = raw_data def __getitem__(self, key): return self._raw[key] @property def display_name(self): """ Find the most appropriate display name for a user: look for a "display_name", then a "real_name", and finally fall back to the always-present "name". """ for k in self._NAME_KEYS: if self._raw.get(k): return self._raw[k] if "profile" in self._raw and self._raw["profile"].get(k): return self._raw["profile"][k] return self._raw["name"] @property def email(self): """ Shortcut property for finding the e-mail address or bot URL. """ if "profile" in self._raw: email = self._raw["profile"].get("email") elif "bot_url" in self._raw: email = self._raw["bot_url"] else: email = None if not email: logging.debug("No email found for %s", self._raw.get("name")) return email def image_url(self, pixel_size=None): """ Get the URL for the user icon in the desired pixel size, if it exists. If no size is supplied, give the URL for the full-size image. """ if "profile" not in self._raw: return profile = self._raw["profile"] if (pixel_size): img_key = "image_%s" % pixel_size if img_key in profile: return profile[img_key] return profile[self._DEFAULT_IMAGE_KEY] def deleted_user(id): """ Create a User object for a deleted user. """ deleted_user = { "id": id, "name": "deleted-" + id, "deleted": True, "is_bot": False, "is_app_user": False, } return User(deleted_user)
hfaran/slack-export-viewer
slackviewer/user.py
Python
mit
2,188